package com.yeyks.commonReference.service.hotel.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeyks.account.dal.dao.AccountInfoMapper;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.account.utils.AccountUtil;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.appcommon.dto.AppAddressDTO;
import com.yeyks.common.appcommon.dto.AppCompanyDTO;
import com.yeyks.common.appcommon.dto.AppPrincipalInfoDTO;
import com.yeyks.common.appcommon.dto.AppStarLevelDTO;
import com.yeyks.common.appcommon.dto.account.AppAccountDTO;
import com.yeyks.common.appcommon.dto.account.AppPayAccountsDTO;
import com.yeyks.common.appcommon.dto.finance.PayAmountFinanceDTO;
import com.yeyks.common.appcommon.dto.hotel.AppHotelBasicDTO;
import com.yeyks.common.appcommon.dto.hotel.AppHotelDetailDTO;
import com.yeyks.common.appcommon.dto.hotel.AppHotelInfoDTO;
import com.yeyks.common.appcommon.dto.hotel.AppHotelTypeDTO;
import com.yeyks.common.appcommon.dto.room.AppRoomDevicesDTO;
import com.yeyks.common.appcommon.dto.room.AppRoomNoteDTO;
import com.yeyks.common.appcommon.json.JsonHotelExtraInfo;
import com.yeyks.common.appcommon.json.JsonHotelPayAccounts;
import com.yeyks.common.appcommon.json.JsonPrincipalInfo;
import com.yeyks.common.appcommon.param.finance.GetIncomeAccountParam;
import com.yeyks.common.appcommon.param.hotel.*;
import com.yeyks.common.appcommon.param.room.SetRoomNoteParam;
import com.yeyks.common.appcommon.result.CommonPage;
import com.yeyks.common.appcommon.result.CommonResult;
import com.yeyks.common.base.PageInfo;
import com.yeyks.common.constants.AccountType;
import com.yeyks.common.constants.ConfigKey;
import com.yeyks.common.constants.HotelStatus;
import com.yeyks.common.dto.mq.EsUpdateMessage;
import com.yeyks.common.em.ComfortEnum;
import com.yeyks.common.em.StarLevelEnum;
import com.yeyks.common.em.SysRoleType;
import com.yeyks.common.em.vip.VipCardTypeEnum;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.param.cnhotel.HotelCountParam;
import com.yeyks.common.result.screen.DataGreenVipHotelMonthResult;
import com.yeyks.common.result.screen.DataScreenHotelStarResult;
import com.yeyks.common.utils.*;
import com.yeyks.common.utils.apputil.bean.MyBeanUtils;
import com.yeyks.common.utils.apputil.enums.DevicesEnum;
import com.yeyks.common.utils.apputil.enums.HotelTypeEnum;
import com.yeyks.common.utils.apputil.redis.RedisService;
import com.yeyks.common.utils.apputil.rediskey.BuilderKey;
import com.yeyks.commonReference.append.rocketmq.service.producer.MQProducerService;
import com.yeyks.commonReference.service.account.AccountInfoService;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.commonReference.service.hotel.HotelInfoService;
import com.yeyks.commonReference.service.hotel.HotelSearchC2bService;
import com.yeyks.commonReference.service.order.OrderPickRecordService;
import com.yeyks.commonReference.service.vip.VipCommissionRateConfigService;
import com.yeyks.commonReference.utils.ConfidentialOperationUtil;
import com.yeyks.commonReference.service.consumer.UserMemberCardService;
import com.yeyks.hotel.dal.dao.*;
import com.yeyks.hotel.dal.domain.*;
import com.yeyks.hotel.dto.*;
import com.yeyks.hotel.param.HotelInfoC2bHotelSearchParam;
import com.yeyks.hotel.param.HotelInfoHotelSearchHotelInfoParam;
import com.yeyks.hotel.param.HotelQueryParam;
import com.yeyks.hotel.param.VipSearchParam;
import com.yeyks.hotel.utils.HotelSearchUtil;
import com.yeyks.hotel.vo.*;
import com.yeyks.order.dal.domain.OrderPickRecord;
import com.yeyks.other.service.AddressDivisionService;
import com.yeyks.search.service.MySearchService;
import com.yeyks.vip.dal.dao.AccountVipSalerRelationMapper;
import com.yeyks.vip.dal.domain.AccountVipSalerRelation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.yeyks.common.utils.apputil.rediskey.RedisKey.ACCOUNT_TOKEN;


/**
 * <p>
 * 酒店信息表 服务实现类
 * </p>
 *
 * @author yun
 * @since 2019-06-25
 */
@Service
@Slf4j
public class HotelInfoServiceImpl extends ServiceImpl<HotelInfoMapper, HotelInfo> implements HotelInfoService {

    @Autowired
    private HotelInfoMapper hotelInfoMapper;
    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Autowired
    private AccountInfoMapper accountInfoMapper;
    @Autowired
    private AccountInfoService accountInfoService;
    @Autowired
    private AccountInfoService sysUserService;
    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private ConfigService configService;
    @Autowired
    private RoomCalendarInfoMapper roomCalendarInfoMapper;
    @Autowired
    private UserMemberCardService userMemberCardService;
    @Autowired
    private AddressDivisionService addressDivisionService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OrderPickRecordService orderPickRecordService;
    @Autowired
    private HotelSearchC2bService hotelC2bSearchService;
    @Autowired
    private AccountVipSalerRelationMapper accountVipSalerRelationMapper;
    @Autowired
    private HotelDeveloperRelationMapper hotelDeveloperRelationMapper;
    @Autowired
    private VipCommissionRateConfigService vipCommissionRateConfigService;
    @Autowired
    private MQProducerService mqProducerService;
    @Autowired
    private MySearchService mySearchService;

    /**
     * 新增酒店(同时需要先增加公司信息，再增加用户，后增加酒店)
     *
     * @param createParam
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public Integer createHotel(HotelCreateParam createParam, AccountInfo loginUser) {
        //首先创建公司，返回创建公司的id
        CompanyInfo companyInfo = changeCompany(createParam);
        Integer c = companyInfoMapper.insertReturnId(companyInfo);
        if (c != 1) {
            throw new ServiceException("创建公司失败");
        }

        List<AccountInfo> existAccount = accountInfoMapper.selectByPhoneOrUsername(null, createParam.getUsername());
        if (existAccount != null && existAccount.size() != 0) {
            if (existAccount.get(0).getValid() != null && existAccount.get(0).getValid().equals(true)) {
                throw new ServiceException("该用户名已经存在");
            }
        }
        //保存子账号登录时候的部门经理id
        Integer managerId = AccountUtil.getOperationUserId(loginUser);

        //接着创建用户，返回创建用户的id
        AccountInfo hotelAccountInfo = changeAccount(createParam);

        //添加用户的时候分配角色处理
        Integer adminId = AccountUtil.getOperationUserId(loginUser); //区县代理id
        if (null != loginUser.getManagerId()) {
            hotelAccountInfo.setParentId(loginUser.getManagerId());
            hotelAccountInfo.setManagerId(null);
            hotelAccountInfo.setStatus(10);
        } else {
            hotelAccountInfo.setParentId(loginUser.getId());
            hotelAccountInfo.setManagerId(null);
        }
        List<Long> roles = new ArrayList<>();
        roles.add(SysRoleType.HotelManager.getIndex());
        hotelAccountInfo.setRoleIdList(roles);
        hotelAccountInfo.setType(AccountType.HotelManager);
        hotelAccountInfo.setDeptId(AccountType.HotelManager);
        hotelAccountInfo.setProvinceCode(createParam.getProvinceCode());
        hotelAccountInfo.setCityCode(createParam.getCityCode());
        hotelAccountInfo.setCountryCode(createParam.getCountryCode());

        accountInfoService.saveUserHotel(hotelAccountInfo);

        AccountInfo newUser = accountInfoMapper.selectByUsername(createParam.getUsername());

        //接着创建酒店
        HotelInfo hotelInfo = changeHotel(createParam);
        //如果不是总公司创建酒店则设置代理关系
        if (loginUser.getType() != AccountType.Administrator) {
            hotelInfo.setAdminId(adminId.intValue());
            AccountInfo countyAgent = null;
            //是子账号
            if (null != managerId) {
                countyAgent = accountInfoService.findByPrimaryKey(managerId);
            }
            if (null != countyAgent) {
                hotelInfo.setCityAgentId(Integer.valueOf(String.valueOf(countyAgent.getParentId()))); //市代id
                AccountInfo cityAgent = accountInfoMapper.selectByPrimaryKey(Integer.valueOf(String.valueOf(countyAgent.getParentId())));
                if (null != cityAgent) {
                    hotelInfo.setProvinceAgentId(Integer.valueOf(String.valueOf(cityAgent.getParentId()))); //省代id
                }
            } else {
                log.info("{}的countyAgent 为空", loginUser.getId());
            }
            hotelInfo.setStatus(HotelStatus.PreSubmit);
        } else {
            //总公司创建直接通过
            hotelInfo.setStatus(HotelStatus.Pass);
            hotelInfo.setVipFlag(0);
            //设置vip佣金比率
//            vipCommissionRateConfigService.addVipCommissionRateConfig(hotelInfo.getOperatorId());
//            saveHotelDeveloperRelation(hotelAccountInfo.getId(), hotelInfo.getDeveloperId());

        }
        hotelInfo.setCompanyId(companyInfo.getId());
        hotelInfo.setOperatorId(newUser.getId());
        hotelInfo.setPrincipalInfo(createParam.getPrincipal());
        hotelInfo.setIsDel(1);
        if (null != createParam.getStartDateNoTax()) {
            hotelInfo.setStartDateNotax(DateUtils.yyyyMMddToDate(createParam.getStartDateNoTax()));
        }
        if (null != createParam.getEndDateNoTax()) {
            hotelInfo.setEndDateNotax(DateUtils.yyyyMMddToDate(createParam.getEndDateNoTax()));
        }

        Integer h = hotelInfoMapper.insert(hotelInfo);
        if (h != 1) {
            throw new ServiceException("创建酒店失败");
        }
        return hotelInfo.getId();
    }

    /**
     * 保存酒店开发商关系
     *
     * @param hotelAccountId
     * @param developerId
     * @param vipType  vip类型，1大V，2小V
     */
    private void saveHotelDeveloperRelation(Integer hotelAccountId, Integer developerId,Integer vipType) {
        HotelDeveloperRelation hotelDeveloperRelation = new HotelDeveloperRelation();
        hotelDeveloperRelation.setAccountId(hotelAccountId);
        hotelDeveloperRelation.setDeveloperId(developerId);
        AccountInfo developer = accountInfoMapper.selectByPrimaryKey(hotelDeveloperRelation.getDeveloperId());
        if (null == developer) {
            throw new ServiceException("开发商不存在");
        }
        if(AccountType.OperateMerchant ==developer.getType()||AccountType.MinOperateMerchant==developer.getType())
        {
            hotelDeveloperRelation.setType(1); //运营商
        }else {
            hotelDeveloperRelation.setType(2);  //服务商
        }
        hotelDeveloperRelation.setVipType(vipType);
        hotelDeveloperRelation.setCreateTime(new Date());
        hotelDeveloperRelationMapper.insert(hotelDeveloperRelation);
    }


    /**
     * 通过酒店id搜索酒店
     *
     * @param hotelId
     * @return
     */
    @Override
    public HotelInfo selectHotelInfoById(Integer hotelId) {
        return hotelInfoMapper.selectByPrimaryKey(hotelId);
    }

    @Override
    public HotelInfo selectHotelInfoByOperatorId(Integer operatorId) {
        return hotelInfoMapper.selectHotelInfoByOperatorId(operatorId);
    }

    /**
     * 根据账号类型查询新增酒店数量
     *
     * @param dtStart
     * @param dtEnd
     * @param type
     * @return
     */
    @Override
    public int getNewHotelCount(Date dtStart, Date dtEnd, Integer id, Integer type) {
        if (type == null || type == 0) {
            return 0;
        }
        return hotelInfoMapper.getNewHotelCount(dtStart, dtEnd, id, type);
    }

    private HotelInfo changeHotel(HotelCreateParam createParam) {

        return ObjectConvertUtil.convertObject(createParam, HotelInfo.class);
    }

    private AccountInfo changeAccount(HotelCreateParam createParam) {

        AccountInfo accountInfo = ObjectConvertUtil.convertObject(createParam, AccountInfo.class);
        accountInfo.setValid(createParam.getAccountValid());
        accountInfo.setType(AccountType.HotelManager);
        accountInfo.setExtraInfo(createParam.getAccountExtraInfo());
        accountInfo.setArea(createParam.getArea());
        return accountInfo;
    }

    private CompanyInfo changeCompany(HotelCreateParam createParam) {
        CompanyInfo companyInfo = ObjectConvertUtil.convertObject(createParam, CompanyInfo.class);
        companyInfo.setExtraInfo(createParam.getHotelExtraInfo());
        companyInfo.setAddress(createParam.getHotelAddress());
        companyInfo.setPrincipalInfo(createParam.getHotelPrincipalInfo());
        return companyInfo;
    }

    //升级酒店为甄选酒店
    @Override
    public AjaxResponseBody upgradeVipHotel(Integer hotelId, Integer developerId,Integer vipFlag) {
        if (null == hotelId) {
            throw new ServiceException("酒店id不能为空");
        }
        if (null == vipFlag) {
            throw new ServiceException("甄选标识不能为空");
        }
        if (vipFlag < 0 ) {
            throw new ServiceException("甄选标识错误");
        }
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(hotelId);
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        QueryWrapper<HotelInfo> queryWrapper = new QueryWrapper<HotelInfo>().eq(HotelInfo.ID,hotelId);
        boolean i = update(new HotelInfo().setVipFlag(vipFlag).setDeveloperId(developerId),queryWrapper);

        if (i) {
            return AjaxResponseBody.success();
        } else {
            return AjaxResponseBody.failed("升级失败");
        }
    }


    @Override
    @Transactional
    public AjaxResponseBody upgradeJipHotel(Integer hotelId, Integer developerId){
        //升级为精选酒店
        if (null == hotelId) {
            throw new ServiceException("酒店id不能为空");
        }

        QueryWrapper queryWrapper = new QueryWrapper<HotelInfo>().eq(HotelInfo.ID,hotelId);

        HotelInfo hotelInfo = baseMapper.selectOne(queryWrapper);

        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }

        //设置优享vip佣金比率
        vipCommissionRateConfigService.addVipCommissionRateConfig(hotelInfo.getOperatorId(),2);
        //保存酒店开发商关系
        saveHotelDeveloperRelation(hotelInfo.getOperatorId(), developerId,2);

        boolean b = update(new HotelInfo().setVipFlag(3).setDeveloperId(developerId), queryWrapper); //设为优享
        if (!b) {
            throw new ServiceException("升级优享酒店失败");
        }else{
            return AjaxResponseBody.success();
        }
    }

    @Override
    public AjaxResponseBody modifyRemark(Integer hotelId, String remark) {
        if (null == hotelId) {
            throw new ServiceException("酒店id不能为空");
        }
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(hotelId);
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        hotelInfo.setRemark(remark).setGmtModified(new Date());
        int i = hotelInfoMapper.updateById(hotelInfo);
        if (i > 0) {
            return AjaxResponseBody.success();
        } else {
            return AjaxResponseBody.failed("修改失败");
        }
    }

    @Override
    public AjaxResponseBody modifyParentTax(Integer hotelId, Integer parentTax) {
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(hotelId);
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        hotelInfo.setParentTax(parentTax).setGmtModified(new Date());
        int i = hotelInfoMapper.updateById(hotelInfo);
        if (i > 0) {
            return AjaxResponseBody.success();
        } else {
            return AjaxResponseBody.failed("修改失败");
        }
    }

    @Override
    public AjaxResponseBody submitHotel(Integer hotelId) {
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(hotelId);
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        hotelInfo.setStatus(com.yeyks.common.em.HotelStatus.PreCheck).setGmtModified(new Date());
        int i = hotelInfoMapper.updateById(hotelInfo);
        if (i > 0) {
            return AjaxResponseBody.success();
        } else {
            return AjaxResponseBody.failed("提交失败");
        }
    }

    @Override
    @Transactional
    public AjaxResponseBody setHotelDeveloper(Integer hotelId, Integer developerId) {
        if (null == hotelId || null == developerId) {
            throw new ServiceException("参数不能为空");
        }
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(hotelId);
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        hotelInfo.setDeveloperId(developerId).setGmtModified(new Date());
        int i = hotelInfoMapper.updateById(hotelInfo);
        if (i > 0) {
            saveHotelDeveloperRelation(hotelInfo.getOperatorId(), developerId,1);
            return AjaxResponseBody.success();
        } else {
            return AjaxResponseBody.failed("修改失败");
        }
    }

    @Override
    public AjaxResponseBody setHotelAgent(Integer hotelId, Integer agentId){
        AccountInfo areaAgent = accountInfoMapper.selectByPrimaryKey(agentId);
        if (null == areaAgent) {
            throw new ServiceException("区代不存在");
        }
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(hotelId);
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        Integer cityAgentId = areaAgent.getParentId(); //市代ID
        AccountInfo cityAgent = accountInfoMapper.selectByPrimaryKey(cityAgentId);
        Integer provinceAgentId = cityAgent.getParentId(); //市代ID
        hotelInfo.setAdminId(agentId).setCityAgentId(cityAgentId).setProvinceAgentId(provinceAgentId).setGmtModified(new Date());
        int i = hotelInfoMapper.updateById(hotelInfo);
        if (i > 0) {
            return AjaxResponseBody.success();
        } else {
            return AjaxResponseBody.failed("设置酒店代理失败");
        }
    }

    @Override
    public List<Map> queryHotelList(HotelQueryParam hotelQueryParam) {

        return hotelInfoMapper.selectByFiltersEx(hotelQueryParam);
    }


    @Override
    public int queryHotelListCount(HotelQueryParam hotelQueryParam) {
        return hotelInfoMapper.selectByFiltersExCount(hotelQueryParam);
    }

    @Override
    public List<Map> queryHotelListByDeveloper(HotelQueryParam hotelQueryParam) {
        return hotelInfoMapper.selectByFiltersEx(getHotelQueryParam(hotelQueryParam));
    }

    @Override
    public int queryHotelListCountByDeveloper(HotelQueryParam hotelQueryParam) {
        return hotelInfoMapper.selectByFiltersExCount(getHotelQueryParam(hotelQueryParam));
    }

    /**
     * 组装查询参数
     *
     * @param hotelQueryParam
     * @return
     */
    private HotelQueryParam getHotelQueryParam(HotelQueryParam hotelQueryParam) {
        //查询开发商下的服务商
        List<Integer> developerIdList = new ArrayList<>();
        if (hotelQueryParam.getUserType() == AccountType.OperateMerchant||AccountType.MinOperateMerchant ==hotelQueryParam.getUserType()) {
            List<AccountVipSalerRelation> vipSalerRelationList = accountVipSalerRelationMapper.selectList(new QueryWrapper<AccountVipSalerRelation>()
                    .eq(AccountVipSalerRelation.PARENT_ID, hotelQueryParam.getLoginUserId()));
            if (!CollectionUtils.isEmpty(vipSalerRelationList)) {
                developerIdList = vipSalerRelationList.stream().map(AccountVipSalerRelation::getAccountId).collect(Collectors.toList());
            }
        }
        developerIdList.add(hotelQueryParam.getLoginUserId());
        hotelQueryParam.setDeveloperIdList(developerIdList);
        return hotelQueryParam;
    }


    @Override
    public List<HotelInfo> searchHotelsNoTaxExpired(Integer id) {
        List<HotelInfo> hotelInfoList = null;
        try {
            hotelInfoList = hotelInfoMapper.searchHotelsNoTaxExpired(id);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return hotelInfoList;
    }

    @Override
    public List<HotelInfo> searchHotelsByAdministrator(Integer id) {
        List<HotelInfo> hotelInfoList = null;
        try {
            hotelInfoList = hotelInfoMapper.selectByAdministrator(id);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return hotelInfoList;
    }

    @Override
    public HotelInfo searchHotelByOperator(Integer id) {
        List<HotelInfo> hotelInfos = searchHotelsByOperator(id);
        return (hotelInfos == null || hotelInfos.size() == 0) ? null : hotelInfos.get(0);
    }

    @Override
    public List<HotelInfo> searchHotelsByOperator(Integer id) {
        List<HotelInfo> hotelInfoList = null;
        try {
            hotelInfoList = hotelInfoMapper.selectByOperator(id);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return hotelInfoList;
    }

    @Override
    public HotelInfo searchHotelByOperator(Integer loginUserId, Integer hotelId) {
        List<HotelInfo> hotelInfoList = this.searchHotelsByOperator(loginUserId);
        for (HotelInfo hotelInfo : hotelInfoList) {
            if (hotelInfo.getId().intValue() == hotelId.intValue()) {
                return hotelInfo;
            }
        }

        return null;
    }

    @Override
    @Transactional
    public int updateValidByIds(Integer hotelId, Boolean status) {
        List<Integer> ids = new ArrayList<>();
        ids.add(hotelId);
        int i = hotelInfoMapper.updateValidByIds(ids, status);
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(hotelId);
        boolean j = false;
        if (null != hotelInfo) {
            j = sysUserService.updateValid(Long.valueOf(hotelInfo.getOperatorId()), status);
        }

        if (i > 0 && j) {
            return 1;
        }
        return 0;
    }

    @Override
    public int updateNoFeeDate(Integer hotelId, Date startDateNoTax, Date endDateNoTax) {
        HotelInfo hotelInfo = new HotelInfo();
        hotelInfo.setStartDateNotax(startDateNoTax);
        hotelInfo.setEndDateNotax(endDateNoTax);
        HotelInfo upHotelInfo = new HotelInfo();
        upHotelInfo.setId(hotelId);
        return baseMapper.update(hotelInfo, new UpdateWrapper<>(upHotelInfo));
    }

    /**
     * 第一单订单完成时设置酒店免用期
     *
     * @param hotelId
     * @param createTime 创建时间
     * @return
     */
    @Override
    public int setNoFeeDateAtFirstOrder(Integer hotelId, Date createTime) {
        HotelInfo hotelInfo = baseMapper.selectByPrimaryKey(hotelId);
        if (null == hotelInfo) {
            return 0;
        }
        if (null != hotelInfo.getNoFeeType()) {
            if (-1 == hotelInfo.getNoFeeType() || 0 == hotelInfo.getNoFeeType())
                return 0;
        }
        //如果免用期有设置则不更新
        if (null != hotelInfo.getStartDateNotax() && null != hotelInfo.getEndDateNotax()) {
            log.info("已经设置过免佣期{}", hotelId);
            return 0;
        }
        if (null == hotelInfo.getNoFeeType()) {
            return 0;
        }
        HotelInfo hotel = new HotelInfo();
        hotel.setGmtModified(DateUtil.date());
        //将createTime格式化为yyyy-MM-dd的日期格式
        DateTime startTime = DateUtil.parseDate(DateUtil.format(createTime, DatePattern.NORM_DATE_PATTERN));
        hotel.setStartDateNotax(startTime);
        //免30天
        if (1 == hotelInfo.getNoFeeType()) {
            hotel.setEndDateNotax(DateUtil.offsetDay(startTime, 30));
        } else if (2 == hotelInfo.getNoFeeType()) {//免60天
            hotel.setEndDateNotax(DateUtil.offsetDay(startTime, 60));
        } else if (3 == hotelInfo.getNoFeeType()) {//免90天
            hotel.setEndDateNotax(DateUtil.offsetDay(startTime, 90));
        }
        HotelInfo upHotelInfo = new HotelInfo();
        upHotelInfo.setId(hotelId);
        return baseMapper.update(hotel, new UpdateWrapper<>(upHotelInfo));
    }


    /**
     * 用户搜索酒店（2民宿，3三星级，4四星级，5五星级，6商务）
     *
     * @param city      城市名称，例：北京
     * @param checkIn   check-in日期，字符串描述，没有时间部分，例：2018-08-13
     * @param checkOut  check-out日期，字符串描述，没有时间部分，例：2018-08-16
     * @param price     价格（单位：分），默认值（0不限价），例：20000 （200元）
     * @param starLevel 星级：默认全部0，2民宿，3星级，6商务
     * @param keyword   关键字，通过酒店的名称
     * @param order     推荐(排序)模式：order 0智能排序（默认是这个），1距离（按照距离升序），2价格（按照价格升序），3价格（按照价格降序）
     * @param pageNum   当前页
     * @param pageSize  页码
     * @param positionX 经度
     * @param positionY 纬度
     * @return
     */
    @Deprecated
    @Override
    public Map<String, Object> searchHotel(String city, Long checkIn, Long checkOut, Integer price, Integer starLevel, String keyword, Integer order, Integer pageNum, Integer pageSize, Double positionX, Double positionY) {

        Map<String, Object> map = new HashMap<>();
        try {
            PageInfo pageInfo = PageInfo.of(pageNum, pageSize);
            String in = null;
            String out = null;
            if (checkIn != null && checkIn != 0) {
                in = DateUtils.stampToYMDStr(checkIn);
            }
            if (checkOut != null && checkOut != 0) {
                out = DateUtils.stampToYMDStr(checkOut);
            }

            map.put("city", city);
            map.put("checkIn", in);
            map.put("checkOut", out);
            map.put("price", price);
            if (starLevel == 0) {
                map.put("starLevel", null);
            } else {
                map.put("starLevel", starLevel);
            }
            if (ArgumentsCheckUtil.notEmpty(keyword)) {
                keyword = keyword.replaceAll("\\s", "");
            }
            map.put("keyword", keyword);
            map.put("order", order);
            map.put("offset", pageInfo.getOffset());
            map.put("limit", pageInfo.getLimit());
            map.put("positionX", positionX);
            map.put("positionY", positionY);
            List<Map> lists = baseMapper.searchHotel(map);
            Integer count = baseMapper.searchHotelCount(map);
            List<UserSearchHotelDTO> userSearchHotelDTOS = new ArrayList<>();
            if (lists == null || lists.size() == 0 || count == 0) {
                map.clear();
                map.put("list", userSearchHotelDTOS);
                map.put("count", count);
                return map;
            }
            //获取一个hotelInfo集合
            Map<Integer, HotelInfo> hotelInfoMap = getHotelInfo(lists);
            Map<Integer, AccountInfo> accountInfoMap = getAccountInfo(hotelInfoMap);
            //通过查询到的酒店的id，获取对应符合条件的房间集合
            Map<Integer, List<RoomInfo>> roomInfosMap = getRoomInfosV2(keyword, price, null, order, lists);
            for (Map list : lists) {
                Integer hotelId = ((Long) list.get("hotelId")).intValue();

                UserSearchHotelDTO userSearchHotelDTO = new UserSearchHotelDTO();
                userSearchHotelDTO.setRoomInfos(roomInfosMap.get(hotelId));
                HotelInfo hotelInfo = hotelInfoMap.get(hotelId);
                HotelSearchDTO hotelSearchDTO = ObjectConvertUtil.convertObject(hotelInfo, HotelSearchDTO.class);
                AccountInfo exist = accountInfoMap.get(hotelInfo.getOperatorId());
                String tel = exist == null ? null : exist.getTel();
                if (!ArgumentsCheckUtil.notEmpty(tel)) {
                    tel = exist == null ? null : exist.getPhone();
                }
                if (!ArgumentsCheckUtil.notEmpty(tel)) {
                    tel = getPhoneByHotelInfo(hotelInfo);
                }
                hotelSearchDTO.setTel(tel);
                userSearchHotelDTO.setHotelInfo(hotelSearchDTO);
                changeStarToStr(userSearchHotelDTO, hotelInfo.getStarLevel());
                Double distance = Double.parseDouble(list.get("distance").toString());
                userSearchHotelDTO.setDistance(distance.intValue());
                userSearchHotelDTOS.add(userSearchHotelDTO);

            }
            map.clear();
            map.put("list", userSearchHotelDTOS);
            map.put("count", count);

        } catch (Exception e) {
            log.error("查询酒店出错{}", e.getLocalizedMessage());
            map.put("list", null);
            map.put("count", 0);
        }
        return map;

    }

    private Map<Integer, List<RoomInfo>> getRoomInfosNew(Integer price, Integer minPrice, List<Map> lists) {
        Map<Integer, List<RoomInfo>> resMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("price", price);
        map.put("minPrice", minPrice);
        for (Map list : lists) {
            Integer hotelId = ((Long) list.get("hotelId")).intValue();
            map.put("hotelId", hotelId);
            List<RoomInfo> roomInfos = roomInfoMapper.selectRoomsByHotelIdNew(map);
            resMap.put(hotelId, roomInfos);
        }
        return resMap;
    }

    private Map<Integer, List<RoomInfo>> getRoomInfosV2(String keyword, Integer price, Integer minPrice, Integer order, List<Map> lists) {
        Map<Integer, List<RoomInfo>> resMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("keyword", keyword);
        map.put("price", price);
        map.put("minPrice", minPrice);
        for (Map list : lists) {
            Integer hotelId = ((Long) list.get("hotelId")).intValue();
            map.put("hotelId", hotelId);
            List<RoomInfo> roomInfos = roomInfoMapper.selectRoomsByHotelId(map);
            //价格升序
            if (order == 2) {
                roomInfos.sort(Comparator.comparing(RoomInfo::getCurPrice));
            }
            //价格降序
            if (order == 3) {
                roomInfos.sort(Comparator.comparing(RoomInfo::getCurPrice).reversed());
            }
            resMap.put(hotelId, roomInfos);
        }
        return resMap;
    }


    /**
     * 通过酒店id计算酒店的平均分
     *
     * @param hotelId
     * @return
     */
    @Override
    public Integer updateScore(Integer hotelId) {
        return baseMapper.updateScore(hotelId);
    }

    /**
     * 通过酒店的id查询酒店的详情
     *
     * @param hotelId
     * @return
     */
    @Override
    public HotelInfoDTO selectHotelRoomDetail(Integer hotelId) {
        HotelInfo hotelInfo = baseMapper.selectById(hotelId);
        if (hotelInfo == null) {
            log.info("该酒店信息不存在{}", hotelId);
            throw new ServiceException("该酒店信息不存在");
        }
        if (hotelInfo.getComfortLevel() == null) {
            hotelInfo.setComfortLevel(1);
        }
        if (hotelInfo.getEnabledCoupon() == null) {
            hotelInfo.setEnabledCoupon(1);
        }
        HotelInfoDTO hotelInfoDTO = ObjectConvertUtil.convertObject(hotelInfo, HotelInfoDTO.class);
        AccountInfo accountInfo = accountInfoMapper.selectById(hotelInfo.getOperatorId());
        if (accountInfo != null && ArgumentsCheckUtil.notEmpty(accountInfo.getTel())) {
            hotelInfoDTO.setPhone(accountInfo.getTel());
        } else {
            String principalInfo = hotelInfo.getPrincipalInfo();
            JSONObject jsonObject = JSONObject.parseObject(principalInfo);
            String phone = (String) jsonObject.get("phone");
            hotelInfoDTO.setPhone(phone);
        }
        changeStarToStr(hotelInfoDTO, hotelInfo.getStarLevel());

        hotelInfoDTO.setComfort(ComfortEnum.getDesc(hotelInfo.getComfortLevel()));
        setHotelPic(hotelInfoDTO, hotelInfo);
        //通过酒店id查询酒店的房间信息
        List<RoomInfo> roomInfos = roomInfoMapper.selectValidByHotelId(hotelId);
        List<RoomInfoDTO> roomInfoDTOS = getRoomInfoDTO(roomInfos, hotelInfoDTO.getEnabledCoupon());
        hotelInfoDTO.setRoomInfoDTOS(roomInfoDTOS);
        return hotelInfoDTO;
    }

    /**
     * 通过酒店的id查询酒店的详情(V2)
     *
     * @param hotelId
     * @return
     */
    @Override
    public HotelInfoV2DTO selectHotelRoomDetailV2(Integer hotelId) {
        HotelInfo hotelInfo = baseMapper.selectById(hotelId);
        if (hotelInfo == null) {
            log.info("该酒店信息不存在{}", hotelId);
            throw new ServiceException("该酒店信息不存在");
        }
        if (hotelInfo.getComfortLevel() == null) {
            hotelInfo.setComfortLevel(1);
        }
        if (hotelInfo.getEnabledCoupon() == null) {
            hotelInfo.setEnabledCoupon(1);
        }
        HotelInfoV2DTO hotelInfoDTO = ObjectConvertUtil.convertObject(hotelInfo, HotelInfoV2DTO.class);
        AccountInfo accountInfo = accountInfoMapper.selectById(hotelInfo.getOperatorId());
        if (accountInfo != null && ArgumentsCheckUtil.notEmpty(accountInfo.getTel())) {
            hotelInfoDTO.setPhone(accountInfo.getTel());
        } else {
            String principalInfo = hotelInfo.getPrincipalInfo();
            JSONObject jsonObject = JSONObject.parseObject(principalInfo);
            String phone = (String) jsonObject.get("phone");
            hotelInfoDTO.setPhone(phone);
        }
        hotelInfoDTO.setStar(StarLevelEnum.getDesc(hotelInfo.getStarLevel()));
        hotelInfoDTO.setComfort(ComfortEnum.getDesc(hotelInfo.getComfortLevel()));
        setHotelPic(hotelInfoDTO, hotelInfo);
        //通过酒店id查询酒店的房间信息
        List<RoomInfo> roomInfos = roomInfoMapper.selectVipByHotelId(hotelId);
        List<RoomInfoDetailDTO> roomInfoDTOS = getRoomInfoDetailDTO(roomInfos, hotelInfo);
        hotelInfoDTO.setRoomInfoDTOS(roomInfoDTOS);
        return hotelInfoDTO;
    }

    /**
     * 通过酒店信息获取酒店联系人的手机号（用于发短信）
     *
     * @param hotelInfo
     * @return
     */
    @Override
    public String getSmsPhoneByHotelInfo(HotelInfo hotelInfo) {
        String phone;
        //通过酒店所有人id查询酒店用户手机号
        AccountInfo accountInfo = accountInfoMapper.selectById(hotelInfo.getOperatorId());
        phone = accountInfo == null ? null : accountInfo.getPhone();
        if (phone == null) {
            phone = getPhoneByHotelInfo(hotelInfo);
        }
        if (phone == null) {
            log.info("该酒店归属用户手机号不存在,hotelId = {}", hotelInfo.getId());
        }
        return phone;
    }

    /**
     * 通过酒店信息获取酒店固话，没有使用手机号
     *
     * @param hotelInfo
     * @return
     */
    @Override
    public String getTelByHotelInfo(HotelInfo hotelInfo) {
        String tel;
        //通过酒店所有人id查询酒店用户手机号
        AccountInfo accountInfo = accountInfoMapper.selectById(hotelInfo.getOperatorId());
        tel = accountInfo == null ? null : accountInfo.getTel();
        if (tel == null) {
            tel = accountInfo == null ? null : accountInfo.getPhone();
        }
        if (tel == null) {
            tel = getPhoneByHotelInfo(hotelInfo);
        }
        if (tel == null) {
            log.info("该酒店固话不存在,hotelId = {}", hotelInfo.getId());
        }
        return tel;
    }

    /**
     * 用户搜索酒店新接口(通过星级)（2民宿，3三星级，4四星级，5五星级，6商务）
     *
     * @param city      城市名称，例：北京
     * @param checkIn   check-in日期，字符串描述，没有时间部分，例：2018-08-13
     * @param checkOut  check-out日期，字符串描述，没有时间部分，例：2018-08-16
     * @param price     价格（单位：分），默认值（0不限价），例：20000 （200元）
     * @param starLevel 星级：默认全部0，2民宿，3星级，6商务
     * @param positionX 经度
     * @param positionY 纬度
     * @return
     */
    @Deprecated
    @Override
    public Map<String, Object> searchHotelNew(String city, Long checkIn, Long checkOut, Integer price, Integer starLevel, Double positionX, Double positionY) {
        List<UserSearchHotelDTO> userSearchHotelDTOS = new ArrayList<>();
        String in = null;
        String out = null;
        if (checkIn != null && checkIn != 0) {
            in = DateUtils.stampToYMDStr(checkIn);
        }
        if (checkOut != null && checkOut != 0) {
            out = DateUtils.stampToYMDStr(checkOut);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("city", city);
        map.put("checkIn", in);
        map.put("checkOut", out);
        map.put("price", price);
        if (starLevel == 0) {
            map.put("starLevel", null);
        } else {
            map.put("starLevel", starLevel);
        }
        map.put("positionX", positionX);
        map.put("positionY", positionY);
        Integer maxDistance;//距离范围
        Integer range;//price的75%
        Integer minCount = null;//搜索酒店最小数
        Integer maxCount = null;//搜索酒店最大数
        Integer limit;//搜索酒店范围
        String title = null;//搜索标题
        String noMessage = null;//没有酒店文案
        String message = null;//有酒店但没该价格区间的酒店
        try {
            String value = configService.getValue(ConfigKey.SEARCH_CONDITION);
            JSONObject jsonObject = JSONObject.parseObject(value);
            maxDistance = (Integer) jsonObject.get("distance");
            range = (Integer) jsonObject.get("range");
            minCount = (Integer) jsonObject.get("minCount");
            maxCount = (Integer) jsonObject.get("maxCount");
            limit = (Integer) jsonObject.get("limit");
            title = (String) jsonObject.get("title");
            noMessage = (String) jsonObject.get("noMessage");
            message = (String) jsonObject.get("message");
        } catch (Exception e) {
            maxDistance = 20000;
            range = 75;
            minCount = 5;
            maxCount = 15;
            limit = 100;
            title = "搜索结果";
            noMessage = "该地区酒店较少";
            message = "该地区酒店较少，请调整价格重新抢单";
        }
        Integer minPrice = FormatUtils.amountToRate(price, range);
        map.put("distance", maxDistance);
        map.put("minPrice", minPrice);
        map.put("limit", limit);
        List<Map> lists = baseMapper.searchHotelNew(map);
        if (lists == null || lists.size() == 0) {
            map.remove("price");
            List<Map> existLists = baseMapper.searchHotelNoPrice(map);
            map.clear();
            map.put("title", title);
            map.put("list", userSearchHotelDTOS);
            if (existLists == null || existLists.size() == 0) {
                map.put("message", noMessage);
            } else {
                map.put("message", message);
            }
            return map;
        }
        //获取一个hotelInfo集合
        Map<Integer, HotelInfo> hotelInfoMap = getHotelInfo(lists);
        Map<Integer, AccountInfo> accountInfoMap = getAccountInfo(hotelInfoMap);
        //通过查询到的酒店的id，获取对应符合条件的房间集合
        Map<Integer, List<RoomInfo>> roomInfosMap = getRoomInfosNew(price, minPrice, lists);
        for (Map list : lists) {
            Integer hotelId = ((Long) list.get("hotelId")).intValue();
            UserSearchHotelDTO userSearchHotelDTO = new UserSearchHotelDTO();
            userSearchHotelDTO.setRoomInfos(roomInfosMap.get(hotelId));
            HotelInfo hotelInfo = hotelInfoMap.get(hotelId);
            if (hotelInfo.getEnabledCoupon() == null) {
                hotelInfo.setEnabledCoupon(1);
            }
            HotelSearchDTO hotelSearchDTO = ObjectConvertUtil.convertObject(hotelInfo, HotelSearchDTO.class);
            AccountInfo exist = accountInfoMap.get(hotelInfo.getOperatorId());
            String tel = exist == null ? null : exist.getTel();
            if (!ArgumentsCheckUtil.notEmpty(tel)) {
                tel = exist == null ? null : exist.getPhone();
            }
            if (!ArgumentsCheckUtil.notEmpty(tel)) {
                tel = getPhoneByHotelInfo(hotelInfo);
            }
            hotelSearchDTO.setTel(tel);
            userSearchHotelDTO.setHotelInfo(hotelSearchDTO);
            changeStarToStr(userSearchHotelDTO, hotelInfo.getStarLevel());
            try {
                Double distance = Double.parseDouble(list.get("distance").toString());
                userSearchHotelDTO.setDistance(distance.intValue());
            } catch (Exception e) {
                userSearchHotelDTO.setDistance(0);
            }
            userSearchHotelDTOS.add(userSearchHotelDTO);

        }
        map.clear();
        map.put("title", title);
        int index = 0;
        try {
            index = Utility.getRandom(minCount, maxCount);
        } catch (Exception e) {
            map.put("list", userSearchHotelDTOS);
            return map;
        }
        if (userSearchHotelDTOS.size() > index) {
            Collections.shuffle(userSearchHotelDTOS);
            map.put("list", userSearchHotelDTOS.subList(0, index));

        } else {
            map.put("list", userSearchHotelDTOS);
        }
        return map;

    }

    /**
     * 用户搜索酒店(通过舒适度)（默认1舒适 2高档 3豪华 4民宿专区）
     *
     * @param city      城市名称，例：北京
     * @param checkIn   check-in日期，字符串描述，没有时间部分，例：2018-08-13
     * @param checkOut  check-out日期，字符串描述，没有时间部分，例：2018-08-16
     * @param price     价格（单位：分），默认值（0不限价），例：20000 （200元）
     * @param starLevel 星级：默认1舒适 2高档 3豪华 4民宿专区
     * @param positionX 经度
     * @param positionY 纬度
     * @return
     */
    @Deprecated
    @Override
    public Map<String, Object> searchHotelV2(String city, Long checkIn, Long checkOut, Integer price, Integer starLevel, Double positionX, Double positionY) {
        List<UserSearchHotelDTO> userSearchHotelDTOS = new ArrayList<>();
        String in = null;
        String out = null;
        if (checkIn != null && checkIn != 0) {
            in = DateUtils.stampToYMDStr(checkIn);
        }
        if (checkOut != null && checkOut != 0) {
            out = DateUtils.stampToYMDStr(checkOut);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("city", city);
        map.put("checkIn", in);
        map.put("checkOut", out);
        map.put("price", price);
        if (starLevel == 0) {
            map.put("starLevel", null);
        } else {
            map.put("starLevel", starLevel);
        }
        map.put("positionX", positionX);
        map.put("positionY", positionY);
        Integer maxDistance;//距离范围
        Integer range;//price的75%
        Integer minCount = null;//搜索酒店最小数
        Integer maxCount = null;//搜索酒店最大数
        Integer limit;//搜索酒店范围
        String title = null;//搜索标题
        String noMessage = null;//没有酒店文案
        String message = null;//有酒店但没该价格区间的酒店
        try {
            String value = configService.getValue(ConfigKey.SEARCH_CONDITION);
            JSONObject jsonObject = JSONObject.parseObject(value);
            maxDistance = (Integer) jsonObject.get("distance");
            range = (Integer) jsonObject.get("range");
            minCount = (Integer) jsonObject.get("minCount");
            maxCount = (Integer) jsonObject.get("maxCount");
            limit = (Integer) jsonObject.get("limit");
            title = (String) jsonObject.get("title");
            noMessage = (String) jsonObject.get("noMessage");
            message = (String) jsonObject.get("message");
        } catch (Exception e) {
            maxDistance = 20000;
            range = 75;
            minCount = 5;
            maxCount = 15;
            limit = 100;
            title = "搜索结果";
            noMessage = "该地区酒店较少";
            message = "该地区酒店较少，请调整价格重新抢单";
        }
        Integer minPrice = FormatUtils.amountToRate(price, range);
        map.put("distance", maxDistance);
        map.put("minPrice", minPrice);
        map.put("limit", limit);
        List<Map> lists = baseMapper.searchHotelV2(map);
        if (lists != null && lists.size() < 5) {
            map.put("distance", maxDistance * 2);
            lists = baseMapper.searchHotelV2(map);
            if (lists.size() < 5) {
                map.put("distance", maxDistance * 4);
                lists = baseMapper.searchHotelV2(map);
            }
        }
        if (lists == null || lists.size() == 0) {
            map.remove("price");
            List<Map> existLists = baseMapper.searchHotelNoPriceV2(map);
            map.clear();
            map.put("title", title);
            map.put("list", userSearchHotelDTOS);
            if (existLists == null || existLists.size() == 0) {
                map.put("message", noMessage);
            } else {
                map.put("message", message);
            }
            return map;
        }
        //获取一个hotelInfo集合
        Map<Integer, HotelInfo> hotelInfoMap = getHotelInfo(lists);
        Map<Integer, AccountInfo> accountInfoMap = getAccountInfo(hotelInfoMap);
        //通过查询到的酒店的id，获取对应符合条件的房间集合
        Map<Integer, List<RoomInfo>> roomInfosMap = getRoomInfosNew(price, minPrice, lists);
        for (Map list : lists) {
            Integer hotelId = ((Long) list.get("hotelId")).intValue();
            UserSearchHotelDTO userSearchHotelDTO = new UserSearchHotelDTO();
            userSearchHotelDTO.setRoomInfos(roomInfosMap.get(hotelId));
            HotelInfo hotelInfo = hotelInfoMap.get(hotelId);
            HotelSearchDTO hotelSearchDTO = ObjectConvertUtil.convertObject(hotelInfo, HotelSearchDTO.class);
            AccountInfo exist = accountInfoMap.get(hotelInfo.getOperatorId());
            String tel = exist == null ? null : exist.getTel();
            if (!ArgumentsCheckUtil.notEmpty(tel)) {
                tel = exist == null ? null : exist.getPhone();
            }
            if (!ArgumentsCheckUtil.notEmpty(tel)) {
                tel = getPhoneByHotelInfo(hotelInfo);
            }
            hotelSearchDTO.setTel(tel);
            userSearchHotelDTO.setHotelInfo(hotelSearchDTO);
            userSearchHotelDTO.setStar(ComfortEnum.getDesc(hotelInfo.getComfortLevel()));
            try {
                Double distance = Double.parseDouble(list.get("distance").toString());
                userSearchHotelDTO.setDistance(distance.intValue());
            } catch (Exception e) {
                userSearchHotelDTO.setDistance(0);
            }
            userSearchHotelDTOS.add(userSearchHotelDTO);

        }
        map.clear();
        map.put("title", title);
        int index = 0;
        try {
            index = Utility.getRandom(minCount, maxCount);
        } catch (Exception e) {
            userSearchHotelDTOS.sort(Comparator.comparing(UserSearchHotelDTO::getDistance));
            map.put("list", userSearchHotelDTOS);
            return map;
        }
        if (userSearchHotelDTOS.size() > index) {
            Collections.shuffle(userSearchHotelDTOS);
            List<UserSearchHotelDTO> changeList = userSearchHotelDTOS.subList(0, index);
            changeList.sort(Comparator.comparing(UserSearchHotelDTO::getDistance));
            map.put("list", userSearchHotelDTOS.subList(0, index));

        } else {
            userSearchHotelDTOS.sort(Comparator.comparing(UserSearchHotelDTO::getDistance));
            map.put("list", userSearchHotelDTOS);
        }
        return map;
    }

    /**
     * 臻选酒店搜索
     *
     * @param param
     * @return
     */
    @Deprecated
    @Override
    public Map<String, Object> vipHotelSearch(VipSearchParam param) {
        try {
            List<VipSearchHotelDTO> vipSearchHotelDTOS = new ArrayList<>();
            String in = null;
            String out = null;
            if (param.getCheckIn() != null && param.getCheckIn() != 0) {
                in = DateUtils.stampToYMDStr(param.getCheckIn());
            }
            if (param.getCheckOut() != null && param.getCheckOut() != 0) {
                out = DateUtils.stampToYMDStr(param.getCheckOut());
            }
            List<Integer> comforts = Splitters.splitToInteger(param.getComfort(), Splitters.COMMA);
            PageInfo of = PageInfo.of(param.getPageNum(), param.getPageSize());
            Map<String, Object> map = Maps.newHashMap();
            map.put("city", param.getCity());
            map.put("checkIn", in);
            map.put("checkOut", out);
            map.put("keyword", param.getKeyword());
            map.put("sort", param.getSort());
            map.put("comforts", comforts);
            map.put("offset", of.getOffset());
            map.put("limit", of.getLimit());
            map.put("positionX", param.getPositionX());
            map.put("positionY", param.getPositionY());
            Map<String, Object> conditionMap = getConditionMap();
            Integer maxDistance = (Integer) conditionMap.get("maxDistance");
            map.put("maxDistance", maxDistance);
            List<VipSearchResult> vipSearchResults = baseMapper.vipHotelSearch(map);
            Integer count = baseMapper.vipHotelSearchCount(map);
            if (vipSearchResults == null || vipSearchResults.size() == 0 || count == 0) {
                map.clear();
                map.put("message", conditionMap.get("noMessage"));
                map.put("list", vipSearchResults);
                map.put("count", count);
                return map;
            }
            //获取一个酒店map
            Map<Integer, HotelInfo> vipHotelMap = getVipHotelInfo(vipSearchResults);
            //获取一个酒店账户Map
            Map<Integer, AccountInfo> accountInfoMap = getAccountInfo(vipHotelMap);
            //获取酒店房间Map
            Map<Integer, List<VipSearchRoomDTO>> vipRoomInfos = getVipRoomInfos(param.getSort(), vipSearchResults);
            for (VipSearchResult vipSearchResult : vipSearchResults) {
                VipSearchHotelDTO vipSearchHotelDTO = new VipSearchHotelDTO();
                vipSearchHotelDTO.setRoomInfos(vipRoomInfos.get(vipSearchResult.getHotelId()));
                HotelInfo hotelInfo = vipHotelMap.get(vipSearchResult.getHotelId());
                HotelSearchDTO hotelSearchDTO = ObjectConvertUtil.convertObject(hotelInfo, HotelSearchDTO.class);
                AccountInfo exist = accountInfoMap.get(hotelInfo.getOperatorId());
                String tel = exist == null ? null : exist.getTel();
                if (!ArgumentsCheckUtil.notEmpty(tel)) {
                    tel = exist == null ? null : exist.getPhone();
                }
                if (!ArgumentsCheckUtil.notEmpty(tel)) {
                    tel = getPhoneByHotelInfo(hotelInfo);
                }
                if (hotelSearchDTO != null) {
                    hotelSearchDTO.setTel(tel);
                }
                vipSearchHotelDTO.setHotelInfo(hotelSearchDTO);
                vipSearchHotelDTO.setStar(ComfortEnum.getDesc(hotelInfo.getComfortLevel()));
                vipSearchHotelDTO.setDistance(vipSearchResult.getDistance());
                vipSearchHotelDTOS.add(vipSearchHotelDTO);
            }
            map.clear();
            map.put("list", vipSearchHotelDTOS);
            map.put("count", count);
            return map;
        } catch (Exception e) {
            log.error("臻选酒店搜索异常{}", e.getLocalizedMessage());
            e.printStackTrace();
        }
        return Maps.newHashMap();
    }

    /**
     * 通过酒店id获取酒店集合
     *
     * @param hotelIds
     * @return
     */
    @Override
    public List<HotelInfo> selectByIds(List<Integer> hotelIds) {
        return baseMapper.selectByIds(hotelIds);
    }

    private Map<String, Object> getConditionMap() {
        Map<String, Object> map = Maps.newHashMap();
        try {
            String value = configService.getValue(ConfigKey.VIP_SEARCH_CONDITION);
            JSONObject jsonObject = JSONObject.parseObject(value);
            map.put("maxDistance", jsonObject.get("distance"));
            map.put("noMessage", jsonObject.get("noMessage"));
        } catch (Exception e) {
            e.printStackTrace();
            map.put("maxDistance", 20000);
            map.put("noMessage", "该地区酒店较少");
        }
        return map;
    }

    private Map<Integer, List<VipSearchRoomDTO>> getVipRoomInfos(Integer sort, List<VipSearchResult> vipSearchResults) {
        try {
            Map<Integer, List<VipSearchRoomDTO>> resMap = new HashMap<>();
            Map<String, Object> map = new HashMap<>();
            for (VipSearchResult vipSearchResult : vipSearchResults) {
                map.put("hotelId", vipSearchResult.getHotelId());
                List<RoomInfo> roomInfos = roomInfoMapper.vipSelectRoomsByHotelId(map);
                List<VipSearchRoomDTO> vipSearchRoomDTOS = ObjectConvertUtil.convertList(roomInfos, VipSearchRoomDTO.class);
                //价格升序
                if (sort == 3) {
                    vipSearchRoomDTOS.sort(Comparator.comparing(VipSearchRoomDTO::getVipDiscountPrice));
                }
                //价格降序
                if (sort == 4) {
                    vipSearchRoomDTOS.sort(Comparator.comparing(VipSearchRoomDTO::getVipDiscountPrice).reversed());
                }
                resMap.put(vipSearchResult.getHotelId(), vipSearchRoomDTOS);
            }
            return resMap;
        } catch (Exception e) {
            log.error("房间转换失败{}", e.getLocalizedMessage());
            e.printStackTrace();
        }
        return Maps.newHashMap();
    }

    private Map<Integer, HotelInfo> getVipHotelInfo(List<VipSearchResult> lists) {
        LinkedHashSet<Integer> set = new LinkedHashSet<>();
        for (VipSearchResult vipSearchResult : lists) {
            set.add(vipSearchResult.getHotelId());
        }
        List<HotelInfo> hotelInfos = baseMapper.selectByIds(new ArrayList<>(set));
        for (HotelInfo hotelInfo : hotelInfos) {
            hotelInfo.setEnabledCoupon(0);
        }
        return Maps.uniqueIndex(hotelInfos, HotelInfo::getId);
    }

    private String getPhoneByHotelInfo(HotelInfo hotelInfo) {
        String phone;
        try {
            JSONObject jsonObject = JSONObject.parseObject(hotelInfo.getPrincipalInfo());
            phone = (String) jsonObject.get("phone");
            return phone;
        } catch (Exception e) {
            return null;
        }
    }

    private void setHotelPic(HotelInfoDTO hotelInfoDTO, HotelInfo hotelInfo) {
        String extraInfo = hotelInfo.getExtraInfo();
        JSONObject jsonObject = JSONObject.parseObject(extraInfo);
        List<String> imgUrlList = (List<String>) jsonObject.get("imgUrlList");
        hotelInfoDTO.setHotelPics(imgUrlList);
    }

    private void setHotelPic(HotelInfoV2DTO hotelInfoDTO, HotelInfo hotelInfo) {
        String extraInfo = hotelInfo.getExtraInfo();
        JSONObject jsonObject = JSONObject.parseObject(extraInfo);
        List<String> imgUrlList = (List<String>) jsonObject.get("imgUrlList");
        hotelInfoDTO.setHotelPics(imgUrlList);
    }

    private List<RoomInfoDetailDTO> getRoomInfoDetailDTO(List<RoomInfo> roomInfos, HotelInfo hotelInfo) {
        List<RoomInfoDetailDTO> roomInfoDTOS = new ArrayList<>();
        for (RoomInfo roomInfo : roomInfos) {
            try {
                RoomInfoDetailDTO detailDTO = ObjectConvertUtil.convertObject(roomInfo, RoomInfoDetailDTO.class);
                String extraInfo = roomInfo.getExtraInfo();
                JSONObject jsonObject = JSONObject.parseObject(extraInfo);
                if (jsonObject != null) {
                    List<String> imgUrlList = (List<String>) jsonObject.get("imgUrlList");
                    detailDTO.setPicUrls(imgUrlList);
                }
                //通过房间id查询酒店
                if (hotelInfo.getEnabledCoupon() == null) {
                    hotelInfo.setEnabledCoupon(1);
                }
                detailDTO.setHotelName(hotelInfo.getName());
                detailDTO.setHotelId(hotelInfo.getId());
                detailDTO.setEnabledCoupon(hotelInfo.getEnabledCoupon());
                roomInfoDTOS.add(detailDTO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return roomInfoDTOS;
    }

    private List<RoomInfoDTO> getRoomInfoDTO(List<RoomInfo> roomInfos, Integer isUse) {
        List<RoomInfoDTO> roomInfoDTOS = new ArrayList<>();
        for (RoomInfo roomInfo : roomInfos) {
            RoomInfoDTO roomInfoDTO = ObjectConvertUtil.convertObject(roomInfo, RoomInfoDTO.class);
            roomInfoDTO.setEnabledCoupon(isUse);
            String extraInfo = roomInfo.getExtraInfo();
            JSONObject jsonObject = JSONObject.parseObject(extraInfo);
            List<String> imgUrlList = (List<String>) jsonObject.get("imgUrlList");
            roomInfoDTO.setPicUrls(imgUrlList);
            roomInfoDTOS.add(roomInfoDTO);
        }
        return roomInfoDTOS;
    }

    private void changeStarToStr(HotelInfoDTO hotelInfoDTO, Integer starLevel) {

        if (starLevel.equals(StarLevelEnum.HOMESTAY.value())) {
            hotelInfoDTO.setStar(StarLevelEnum.HOMESTAY.desc());
        }
        if (starLevel.equals(StarLevelEnum.THREESTAR.value())) {
            hotelInfoDTO.setStar(StarLevelEnum.THREESTAR.desc());
        }
        if (starLevel.equals(StarLevelEnum.FOURSTAR.value())) {
            hotelInfoDTO.setStar(StarLevelEnum.FOURSTAR.desc());
        }
        if (starLevel.equals(StarLevelEnum.FIVESTAR.value())) {
            hotelInfoDTO.setStar(StarLevelEnum.FIVESTAR.desc());
        }
        if (starLevel.equals(StarLevelEnum.BUSINESS.value())) {
            hotelInfoDTO.setStar(StarLevelEnum.BUSINESS.desc());
        }
    }

    private void changeStarToStr(UserSearchHotelDTO userSearchHotelDTO, Integer starLevel) {

        if (starLevel.equals(StarLevelEnum.HOMESTAY.value())) {
            userSearchHotelDTO.setStar(StarLevelEnum.HOMESTAY.desc());
        }
        if (starLevel.equals(StarLevelEnum.THREESTAR.value())) {
            userSearchHotelDTO.setStar(StarLevelEnum.THREESTAR.desc());
        }
        if (starLevel.equals(StarLevelEnum.FOURSTAR.value())) {
            userSearchHotelDTO.setStar(StarLevelEnum.FOURSTAR.desc());
        }
        if (starLevel.equals(StarLevelEnum.FIVESTAR.value())) {
            userSearchHotelDTO.setStar(StarLevelEnum.FIVESTAR.desc());
        }
        if (starLevel.equals(StarLevelEnum.BUSINESS.value())) {
            userSearchHotelDTO.setStar(StarLevelEnum.BUSINESS.desc());
        }
    }

    private Map<Integer, HotelInfo> getHotelInfo(List<Map> lists) {
        LinkedHashSet<Integer> set = new LinkedHashSet<>();
        for (Map list : lists) {
            set.add(((Long) list.get("hotelId")).intValue());
        }
        List<HotelInfo> hotelInfos = baseMapper.selectByIds(new ArrayList<>(set));
        return Maps.uniqueIndex(hotelInfos, HotelInfo::getId);
    }

    private Map<Integer, AccountInfo> getAccountInfo(Map<Integer, HotelInfo> hotelInfoMap) {
        List<HotelInfo> hotelInfos = new ArrayList<>();
        for (Map.Entry<Integer, HotelInfo> entry : hotelInfoMap.entrySet()) {
            hotelInfos.add(entry.getValue());
        }
        List<Integer> operatorIds = Lists.transform(hotelInfos, HotelInfo::getOperatorId);
        List<AccountInfo> accountInfos = accountInfoMapper.selectByIds(operatorIds);
        Maps.uniqueIndex(accountInfos, AccountInfo::getId);
        return Maps.uniqueIndex(accountInfos, AccountInfo::getId);
    }

    //C2B酒店搜索:v3.3
    @Override
    public HotelInfoC2bHotelSearchVo c2bHotelSearch(HotelInfoC2bHotelSearchParam param) {
        //修正时间
        param.setStartDate(DateUtil.beginOfDay(param.getStartDate()));
        param.setEndDate(DateUtil.beginOfDay(param.getEndDate()));
        //时间校验
        HotelSearchUtil.checkSearchDate(param.getStartDate(), param.getEndDate());
        //获取搜索配置
        Map<String, Object> map = JSONUtil.toBean(configService.getValue(ConfigKey.C2B_SEARCH_CONDITION), Map.class);
        param.setDistance(null != map.get("distance") ? (Integer) map.get("distance") : 5000);
        //返回对象
        ArrayList<HotelInfoC2bHotelSearchVoList> hotelInfoC2bHotelSearchVos = null;
        Integer distance = param.getDistance();
        int count = 3;
        //最大个数
        Integer maxAmount = configService.c2bSearchAmount();
        //循环3次,每次半径扩大一倍,半径初始5000米
        while (count-- > 0 && (CollectionUtil.isEmpty(hotelInfoC2bHotelSearchVos) || hotelInfoC2bHotelSearchVos.size() < maxAmount)) {
            hotelInfoC2bHotelSearchVos = new ArrayList<>();
            //搜索酒店
            List<HotelInfoC2bHotelSearchDto> hotelInfoC2bHotelSearchDtos = hotelInfoMapper.c2bHotelSearch190701(param, distance);
            ArrayList<Integer> hotelIds = new ArrayList<>();
            Long between = DateUtil.between(param.getStartDate(), param.getEndDate(), DateUnit.DAY);
            if (null != hotelInfoC2bHotelSearchDtos && hotelInfoC2bHotelSearchDtos.size() > 0) {
                for (HotelInfoC2bHotelSearchDto hotelInfoC2bHotelSearchDto : hotelInfoC2bHotelSearchDtos) {
                    switch (hotelInfoC2bHotelSearchDto.getStarLevel()) {
                        case 2:
                            hotelInfoC2bHotelSearchDto.setStar("民宿");
                            break;
                        case 3:
                        case 4:
                        case 5:
                            hotelInfoC2bHotelSearchDto.setStar("星级");
                            break;
                        case 6:
                            hotelInfoC2bHotelSearchDto.setStar("商务");
                            break;
                    }
                    hotelIds.add(hotelInfoC2bHotelSearchDto.getId());
                }
                //搜索房间
                List<RoomCalendarInfo> roomCalendarInfos = roomCalendarInfoMapper.c2bRoomCalendarInfoSearch(param, hotelIds, between.intValue());
                if (null != roomCalendarInfos && roomCalendarInfos.size() > 0) {
                    //搜索房间信息
                    ArrayList<Integer> roomIds = new ArrayList<>();
                    for (RoomCalendarInfo roomCalendarInfo : roomCalendarInfos) {
                        roomIds.add(roomCalendarInfo.getRoomId());
                        //去除信息
                        ConfidentialOperationUtil.dealRoomCalendarInfo(roomCalendarInfo);
                    }
                    List<RoomInfo> roomInfos = roomInfoMapper.selectList(new QueryWrapper<RoomInfo>()
                            .eq(RoomInfo.IS_DEL, 1)
                            .in(RoomInfo.ID, roomIds));
                    for (RoomInfo roomInfo : roomInfos) {
                        //去除信息
                        ConfidentialOperationUtil.dealRoomInfo(roomInfo);
                    }
                    //组合结果
                    for (HotelInfoC2bHotelSearchDto hotelInfoC2bHotelSearchDto : hotelInfoC2bHotelSearchDtos) {
                        ArrayList<HotelInfoC2bHotelSearchRoomInfoVo> hotelInfoC2bHotelSearchRoomInfoVos = new ArrayList<>();
                        //如果房态存在就添加到集合
                        for (RoomCalendarInfo roomCalendarInfo : roomCalendarInfos) {
                            if (null != roomCalendarInfo.getHotelId() && roomCalendarInfo.getHotelId().equals(hotelInfoC2bHotelSearchDto.getId())) {
                                HotelInfoC2bHotelSearchRoomInfoVo hotelInfoC2bHotelSearchRoomInfoVo = new HotelInfoC2bHotelSearchRoomInfoVo();
                                hotelInfoC2bHotelSearchRoomInfoVo.setRoomCalendarInfo(roomCalendarInfo);
                                //添加房间信息
                                for (RoomInfo roomInfo : roomInfos) {
                                    if (null != roomCalendarInfo.getRoomId() && roomCalendarInfo.getRoomId().equals(roomInfo.getId())) {
                                        hotelInfoC2bHotelSearchRoomInfoVo.setRoomInfo(roomInfo);
                                        break;
                                    }
                                }
                                hotelInfoC2bHotelSearchRoomInfoVos.add(hotelInfoC2bHotelSearchRoomInfoVo);
                            }
                        }
                        //去除房间信息不存在的房间
                        Iterator<HotelInfoC2bHotelSearchRoomInfoVo> iterator = hotelInfoC2bHotelSearchRoomInfoVos.iterator();
                        while (iterator.hasNext()) {
                            HotelInfoC2bHotelSearchRoomInfoVo hotelInfoC2bHotelSearchRoomInfoVo = iterator.next();
                            if (null == hotelInfoC2bHotelSearchRoomInfoVo.getRoomInfo()) {
                                iterator.remove();
                            }
                        }
                        //如果房态集合存在就添加到返回值里
                        if (hotelInfoC2bHotelSearchRoomInfoVos.size() > 0) {
                            //酒店房间排序
                            hotelInfoC2bHotelSearchRoomInfoVos.sort((o1, o2) -> {
                                return o2.getRoomCalendarInfo().getSalePrice() - o1.getRoomCalendarInfo().getSalePrice();
                            });
                            HotelInfoC2bHotelSearchVoList hotelInfoC2bHotelSearchVo = new HotelInfoC2bHotelSearchVoList();
                            hotelInfoC2bHotelSearchVo.setHotelInfoC2bHotelSearchDto(hotelInfoC2bHotelSearchDto);
                            hotelInfoC2bHotelSearchVo.setDistance(hotelInfoC2bHotelSearchDto.getDistance());
                            hotelInfoC2bHotelSearchVo.setHotelInfoC2bHotelSearchRoomInfoVos(hotelInfoC2bHotelSearchRoomInfoVos);
                            hotelInfoC2bHotelSearchVos.add(hotelInfoC2bHotelSearchVo);
                        }
                    }
                }
            }
            //type 3 的排序,1 2 在slq里排序
            if (!hotelInfoC2bHotelSearchVos.isEmpty() && 3 == param.getSort()) {
                hotelInfoC2bHotelSearchVos.sort((o1, o2) -> {
                    Integer o1Max = 0;
                    for (HotelInfoC2bHotelSearchRoomInfoVo hotelInfoC2bHotelSearchRoomInfoVo : o1.getHotelInfoC2bHotelSearchRoomInfoVos()) {
                        Integer salePrice = hotelInfoC2bHotelSearchRoomInfoVo.getRoomCalendarInfo().getSalePrice();
                        if (salePrice > o1Max) {
                            o1Max = salePrice;
                        }
                    }
                    Integer o2Max = 0;
                    for (HotelInfoC2bHotelSearchRoomInfoVo hotelInfoC2bHotelSearchRoomInfoVo : o2.getHotelInfoC2bHotelSearchRoomInfoVos()) {
                        Integer salePrice = hotelInfoC2bHotelSearchRoomInfoVo.getRoomCalendarInfo().getSalePrice();
                        if (salePrice > o2Max) {
                            o2Max = salePrice;
                        }
                    }
                    return o2Max - o1Max;
                });
            }
            distance *= 2;
        }
        //创建返回对象
        HotelInfoC2bHotelSearchVo hotelInfoC2bHotelSearchVo = new HotelInfoC2bHotelSearchVo();
        hotelInfoC2bHotelSearchVo.setList(hotelInfoC2bHotelSearchVos);
        //没有结果时添加返回信息
        if (hotelInfoC2bHotelSearchVos.isEmpty()) {
            List<HotelInfo> hotelInfos = list(new QueryWrapper<HotelInfo>().like(HotelInfo.ADDRESS, param.getCity()));
            if (hotelInfos.isEmpty()) {
                hotelInfoC2bHotelSearchVo.setMessage(map.get("noMessage").toString());
            } else {
                hotelInfoC2bHotelSearchVo.setMessage(map.get("message").toString());
            }
        }
        return hotelInfoC2bHotelSearchVo;
    }

    //酒店详情:v3.4
    @Override
    public HotelInfoHotelSearchHotelInfoVo hotelSearchHotelInfo(HotelInfoHotelSearchHotelInfoParam param) {
        //修正时间
        param.setStartDate(DateUtil.beginOfDay(param.getStartDate()));
        param.setEndDate(DateUtil.beginOfDay(param.getEndDate()));
//        //时间修正
//        param.setStartDate(HotelSearchUtil.fixDate(param.getStartDate()));
//        param.setEndDate(HotelSearchUtil.fixDate(param.getEndDate()));
        //时间校验
        HotelSearchUtil.checkSearchDate(param.getStartDate(), param.getEndDate());
        HotelInfoHotelSearchHotelInfoVo hotelInfoHotelSearchHotelInfoVo = new HotelInfoHotelSearchHotelInfoVo();
        HotelInfo hotelInfo = getById(param.getHotelId());
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        hotelInfoHotelSearchHotelInfoVo.setHotelInfo(BeanUtil.toBean(hotelInfo, HotelInfoHotelSearchHotelInfoHotelInfoVo.class));
        List<HotelInfoHotelSearchHotelInfoRoomInfoVo> hotelInfoHotelSearchHotelInfoRoomInfoVos;
        switch (param.getVipFlag()) {
            case 1:
                if (!userMemberCardService.checkUserVip(param.getUserId(),VipCardTypeEnum.VIP.getValue())) {
                    throw new ServiceException("非甄选用户不能使用甄选功能");
                }
                hotelInfoHotelSearchHotelInfoRoomInfoVos = roomInfoMapper.hotelSearchRoomInfoInHotelInfo(param);
                for (HotelInfoHotelSearchHotelInfoRoomInfoVo hotelInfoHotelSearchHotelInfoRoomInfoVo : hotelInfoHotelSearchHotelInfoRoomInfoVos) {
                    //去除信息
                    ConfidentialOperationUtil.dealRoomInfo(hotelInfoHotelSearchHotelInfoRoomInfoVo);
                }
                hotelInfoHotelSearchHotelInfoVo.setHotelInfoHotelSearchHotelInfoRoomInfoVos(hotelInfoHotelSearchHotelInfoRoomInfoVos);
                break;
            case 3:
//                if (!userMemberCardService.checkUserVip(param.getUserId(),VipCardTypeEnum.JIP.getValue())) {
//                    throw new ServiceException("非精选用户不能使用精选功能");
//                }
                hotelInfoHotelSearchHotelInfoRoomInfoVos = roomInfoMapper.hotelSearchRoomInfoInJipHotelInfo(param);
                for (HotelInfoHotelSearchHotelInfoRoomInfoVo hotelInfoHotelSearchHotelInfoRoomInfoVo : hotelInfoHotelSearchHotelInfoRoomInfoVos) {
                    //去除信息
                    ConfidentialOperationUtil.dealRoomInfo(hotelInfoHotelSearchHotelInfoRoomInfoVo);
                }
                hotelInfoHotelSearchHotelInfoVo.setHotelInfoHotelSearchHotelInfoRoomInfoVos(hotelInfoHotelSearchHotelInfoRoomInfoVos);
                break;
            case 2:
                List<RoomInfo> roomInfos = roomInfoMapper.selectList(
                        new QueryWrapper<RoomInfo>()
                                .eq(RoomInfo.HOTEL_ID, param.getHotelId())
                                .eq(RoomInfo.IS_DEL, 1)
                                .eq(RoomInfo.VALID, 1)
                );
                List<HotelInfoHotelSearchHotelInfoRoomInfoVo> vos = new ArrayList<>();
                ArrayList<Integer> roomIds = new ArrayList<>();
                for (RoomInfo roomInfo : roomInfos) {
                    roomIds.add(roomInfo.getId());
                    //去除房间多余信息
                    ConfidentialOperationUtil.dealRoomInfo(roomInfo);
                    vos.add(BeanUtil.toBean(roomInfo, HotelInfoHotelSearchHotelInfoRoomInfoVo.class));
                }
                hotelInfoHotelSearchHotelInfoVo.setHotelInfoHotelSearchHotelInfoRoomInfoVos(vos);
                //房态
                List<HotelInfoHotelSearchVoRoomCalendar> hotelInfoB2cHotelSearchVoRoomCalendars = hotelInfoMapper.b2cHotelSearchRoomCalendars(param.getStartDate(), param.getEndDate(), roomIds);
                for (HotelInfoHotelSearchHotelInfoRoomInfoVo vo : vos) {
                    Iterator<HotelInfoHotelSearchVoRoomCalendar> iterator = hotelInfoB2cHotelSearchVoRoomCalendars.iterator();
                    while (iterator.hasNext()) {
                        HotelInfoHotelSearchVoRoomCalendar roomCalendar = iterator.next();
                        if (vo.getId().equals(roomCalendar.getRoomId())) {
                            vo.setSalePrice(roomCalendar.getMinPrice());
                            vo.setRoomCount(roomCalendar.getMinCount());
                        }
                    }
                }
                break;
            case 10:
                //v3.6 删除
                //throw new ServiceException("查询参数有误");
                //查询记录
                List<OrderPickRecord> orderPickRecords = orderPickRecordService.list(
                        new QueryWrapper<OrderPickRecord>()
                                .eq(OrderPickRecord.USER_ID, param.getUserId())
                                .eq(OrderPickRecord.TIMESTAMP, param.getTimestamp())
                                .eq(OrderPickRecord.HOTEL_ID, param.getHotelId())
                );
                if (CollectionUtil.isEmpty(orderPickRecords)) {
                    throw new ServiceException("酒店不存在抢单记录");
                }
                //转对象
                List<HotelInfoHotelSearchVoHotle> hotelInfoHotelSearchVoHotles = hotelC2bSearchService.convertOrderPickRecordsToGrabTheOrderServiceHotelAndRoomVos(orderPickRecords);
                ArrayList<HotelInfoHotelSearchHotelInfoRoomInfoVo> roomInfoVos = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(hotelInfoHotelSearchVoHotles)) {
                    List<HotelInfoHotelSearchVoRoom> hotelInfoHotelSearchVoRooms = hotelInfoHotelSearchVoHotles.get(0).getRooms();
                    if (CollectionUtil.isNotEmpty(hotelInfoHotelSearchVoRooms)) {
                        for (HotelInfoHotelSearchVoRoom hotelInfoHotelSearchVoRoom : hotelInfoHotelSearchVoRooms) {
                            HotelInfoHotelSearchHotelInfoRoomInfoVo hotelInfoHotelSearchHotelInfoRoomInfoVo = BeanUtil.toBean(hotelInfoHotelSearchVoRoom, HotelInfoHotelSearchHotelInfoRoomInfoVo.class);
                            hotelInfoHotelSearchHotelInfoRoomInfoVo.setRoomCount(hotelInfoHotelSearchVoRoom.getMinCount());
                            hotelInfoHotelSearchHotelInfoRoomInfoVo.setSalePrice(hotelInfoHotelSearchVoRoom.getMinPrice());
                            roomInfoVos.add(hotelInfoHotelSearchHotelInfoRoomInfoVo);
                        }
                    }
                }
                hotelInfoHotelSearchHotelInfoVo.setHotelInfoHotelSearchHotelInfoRoomInfoVos(roomInfoVos);
                //v3.6 删除
                break;
            default:
                break;
        }
        return hotelInfoHotelSearchHotelInfoVo;
    }

    /**
     * 根据登录账户获取该账户下的酒店
     *
     * @param accountInfo
     * @return 返回酒店集合
     */
    @Override
    public List<HotelInfo> getHotelInfoByAccountId(AccountInfo accountInfo) {
        if (accountInfo == null) {
            return Lists.newArrayList();
        }
        List<HotelInfo> hotelInfos = hotelInfoMapper.queryHotelByLoginAdmin(AccountUtil.getOperationUserId(accountInfo), accountInfo.getType());
        if (hotelInfos == null || hotelInfos.size() == 0) {
            return Lists.newArrayList();
        }
        return hotelInfos;
    }

    /**
     * 根据登录账户获取该账户下的酒店
     *
     * @param accountInfo
     * @return 返回酒店Id集合
     */
    @Override
    public List<Integer> getHotelInfoByAccountIdToId(AccountInfo accountInfo) {
        if (accountInfo == null) {
            return Lists.newArrayList();
        }
        List<HotelInfo> hotelInfos = getHotelInfoByAccountId(accountInfo);
        if (hotelInfos == null || hotelInfos.size() == 0) {
            return Lists.newArrayList();
        }
        return Lists.transform(hotelInfos, HotelInfo::getId);
    }

    /**
     * 查询该酒店账户的酒店，没有酒店抛异常
     *
     * @param accountInfo
     * @return
     */
    @Override
    public HotelInfo getHotelInfoAccountHotelInfo(AccountInfo accountInfo) {
        HotelInfo hotelInfo = baseMapper.selectOne(new QueryWrapper<HotelInfo>().eq(HotelInfo.OPERATOR_ID, AccountUtil.getOperationUserId(accountInfo)).last("limit 1"));
        if (hotelInfo == null) {
            throw new ServiceException("该账户下无酒店");
        }
        return hotelInfo;
    }

    @Override
    public CommonResult<PayAmountFinanceDTO> getIncomeAccount(GetIncomeAccountParam getIncomeAccountParam, AccountInfo accountInfo) {

        Integer operationUserId = AccountUtil.getOperationUserId(accountInfo);
        PayAmountFinanceDTO payAmountFinanceDTO = null;
        if (AccountType.Administrator == accountInfo.getType() ||
            AccountType.ProvinceManager == accountInfo.getType() ||
            AccountType.CityAgent == accountInfo.getType() ||
            AccountType.CityManager == accountInfo.getType()) {
            //查询酒店账户
            AccountInfo hotelAccountInfo = accountInfoMapper.selectById(operationUserId);
            if (null != hotelAccountInfo) {
                if (!StringUtils.isEmpty(hotelAccountInfo.getExtraInfo())) {
                    payAmountFinanceDTO = jsonToObject(hotelAccountInfo.getExtraInfo());
                }
            }
        } else if (AccountType.HotelManager == accountInfo.getType()) {
            //通过酒店所有人获取酒店
            HotelInfo hotelInfo = baseMapper.selectOne(new QueryWrapper<HotelInfo>().eq(HotelInfo.OPERATOR_ID, operationUserId));
            if (null != hotelInfo) {
                if (!StringUtils.isEmpty(hotelInfo.getPayAccounts())) {
                    payAmountFinanceDTO = jsonToObject(hotelInfo.getPayAccounts());
                }
            }
        }
        return CommonResult.success(payAmountFinanceDTO);
    }

//    /**
//     * 修改绑定银行卡账户
//     *
//     * @param loginUser
//     * @param param
//     * @param updateType 0修改总公司，1修改酒店
//     * @return
//     */
//    @Override
//    public boolean updateBind(AccountInfo loginUser, WithdrawalUpdateCardParam param, Integer updateType) {
//        Map<String, WithdrawalUpdateCardParam> map = Maps.newHashMap();
//        if (AccountType.Administrator != loginUser.getType()) {
//            throw new ServiceException("当前用户无操作权限");
//        }
//        //修改总公司银行卡账户信息
//        if (0 == updateType) {
//            AccountInfo accountInfo = accountInfoService.getById(AccountUtil.getOperationUserId(loginUser));
//            if (null == accountInfo) {
//                log.info("当前操作人login = {}", loginUser);
//                throw new ServiceException("总公司账户不存在");
//            }
//            param.setType(null);
//            map.put("pay_accounts", param);
//            accountInfo.setExtraInfo(JSONObject.toJSONString(map));
//            if (accountInfoMapper.updateById(accountInfo) != 1) {
//                throw new ServiceException("修改总公司银行账户信息失败");
//            }
//        } else {
//            if (null == param.getHotelId()) {
//                throw new ServiceException("修改酒店账户信息酒店id必传");
//            }
//            if (null == param.getType()) {
//                throw new ServiceException("酒店账户类型必传");
//            }
//            HotelInfo hotelInfo = baseMapper.selectById(param.getHotelId());
//            if (null == hotelInfo) {
//                log.info("该酒店不存在hotelId = {}", param.getHotelId());
//                throw new ServiceException("该酒店不存在");
//            }
//            param.setHotelId(null);
//            map.put("pay_accounts", param);
//            hotelInfo.setPayAccounts(JSONObject.toJSONString(map));
//            if (baseMapper.updateById(hotelInfo) != 1) {
//                throw new ServiceException("修改酒店银行账户信息失败");
//            }
//        }
//        return true;
//    }


    /**
     * 从json中获取对象信息
     *
     * @param extraInfo json字符串
     * @return 返回对象信息
     */
    private PayAmountFinanceDTO jsonToObject(String extraInfo) {

        PayAmountFinanceDTO payAmountFinanceDTO = null;
        JsonHotelPayAccounts hotelPayAccounts = JSONObject.parseObject(extraInfo,
                JsonHotelPayAccounts.class);
        if (null != hotelPayAccounts && null != hotelPayAccounts.getPay_accounts()) {
            payAmountFinanceDTO = MyBeanUtils.convert(hotelPayAccounts.getPay_accounts(), PayAmountFinanceDTO.class);
        }
        return payAmountFinanceDTO;
    }

    //==============admin - app 实现方法=========================

    @Override
    public CommonResult<CommonPage<AppHotelBasicDTO>> listPage(QueryHotelParam queryHotelParam, AccountInfo accountInfo) {

        if (accountInfo.getType() == AccountType.HotelManager) {
            log.warn("该ID为[{}]账户没有权限", accountInfo.getId());
            return CommonResult.create(null, CommonResult.NO_PERMISSION, "没有权限访问");
        }

        CommonPage<AppHotelBasicDTO> commonPage = CommonPage.restPage(queryHotelParam.getPageNum(),
                queryHotelParam.getLastId(), new ArrayList<AppHotelBasicDTO>());
        //组装查询数据
        Map<String, Object> queryMap = convertQueryMap(queryHotelParam, accountInfo);
        PageHelper.startPage(queryHotelParam.getPageNum(), queryHotelParam.getPageSize());
        List<HotelInfo> list = hotelInfoMapper.queryPageByParam(queryMap);
        if (!CollectionUtils.isEmpty(list)) {
            CommonPage<HotelInfo> hotelInfoCommonPage = CommonPage.restPage(queryHotelParam.getPageNum(),
                    queryHotelParam.getLastId(), list);
            commonPage = MyBeanUtils.convertCommonPageList(hotelInfoCommonPage, AppHotelBasicDTO.class);
            //执行数据的组装
            commonPage.getList().forEach(appHotelBasicDTO -> {
                //酒店图片
                JsonHotelExtraInfo hotelExtraInfo = JSONObject.parseObject(appHotelBasicDTO.getExtraInfo(), JsonHotelExtraInfo.class);
                appHotelBasicDTO.setHotelPics(hotelExtraInfo.getImgUrlList());
                appHotelBasicDTO.setRoomInfoDTOList(Lists.newArrayList());
            });
        }

        return CommonResult.success(commonPage);
    }

    @Override
    public CommonResult<CommonPage<AppHotelBasicDTO>> queryListByAccountId(QueryHotelByAccountIdParam param, AccountInfo convert) {

        AccountInfo accountInfo = accountInfoMapper.selectByPrimaryKey(param.getAccountId());
        if (accountInfo != null) {
            if (accountInfo.getManagerId() != null) {
                //子账号查询酒店，需要managerId去查询
                param.setAccountId(accountInfo.getManagerId());
            }
        }
        //根据区域查酒店
        String areaType = null;
        CommonResult<AppAddressDTO> addressDTOCommonResult = addressDivisionService.getAddressByDivId(param.getDivCode());
        if (null != addressDTOCommonResult.getData()) {
            areaType = addressDTOCommonResult.getData().getDivLevel();
        }
        Map<String, Object> queryMap = ObjectConvertUtil.objectToMap(param);
        assert queryMap != null;
        queryMap.put("areaType", areaType);
        List<HotelInfo> appHotelInfoList = Lists.newArrayList();
        if(accountInfo.getType() == AccountType.MinOperateMerchant){
            PageHelper.startPage(param.getPageNum(), param.getPageSize());
            appHotelInfoList = hotelInfoMapper.queryPageByBusinessId(queryMap);
        }else{
            PageHelper.startPage(param.getPageNum(), param.getPageSize());
            appHotelInfoList = hotelInfoMapper.queryPageByAccountId(queryMap);
        }
        CommonPage<AppHotelBasicDTO> commonPage = CommonPage.restPage(param.getPageNum(), param.getLastId(), Lists.newArrayList());
        if (!org.springframework.util.CollectionUtils.isEmpty(appHotelInfoList)) {
            CommonPage<HotelInfo> hotelInfoCommonPage = CommonPage.restPage(param.getPageNum(),
                    param.getLastId(), appHotelInfoList);
            commonPage = MyBeanUtils.convertCommonPageList(hotelInfoCommonPage, AppHotelBasicDTO.class);
            commonPage.getList().forEach(appHotelBasicDTO -> {
                //酒店图片
                if (null != appHotelBasicDTO.getExtraInfo() && !"".equals(appHotelBasicDTO.getExtraInfo())) {
                    JsonHotelExtraInfo hotelExtraInfo = JSONObject.parseObject(appHotelBasicDTO.getExtraInfo(), JsonHotelExtraInfo.class);
                    appHotelBasicDTO.setHotelPics(hotelExtraInfo.getImgUrlList());
                }
            });
        }
        return CommonResult.success(commonPage);
    }

    @Override
    public CommonResult<AppHotelDetailDTO> getHotelDetail(GetHotelDetailParam getHotelDetailParam, AccountInfo accountInfo) {

        AppHotelDetailDTO detailDTO = new AppHotelDetailDTO();
        AppHotelInfoDTO hotelInfoDTO = new AppHotelInfoDTO();
        AppCompanyDTO companyDTO = new AppCompanyDTO();
        AppAccountDTO accountDTO = new AppAccountDTO();
        AppPayAccountsDTO payAccountsDTO = new AppPayAccountsDTO();
        //判断是否查询所有(是否是酒店账号)
        if (getHotelDetailParam.getAll() && accountInfo.getType() != AccountType.HotelManager) {
            //根据酒店id 查询
            HotelInfo appHotelInfo = hotelInfoMapper.selectByPrimaryKey(getHotelDetailParam.getId());
            if (null != appHotelInfo) {
                //酒店信息
                hotelInfoDTO = MyBeanUtils.convert(appHotelInfo, AppHotelInfoDTO.class);

                //查询公司信息
                CompanyInfo appCompanyInfo = companyInfoMapper.selectByPrimaryKey(appHotelInfo.getCompanyId());
                if (null != appCompanyInfo) {
                    companyDTO = MyBeanUtils.convert(appCompanyInfo, AppCompanyDTO.class);
                    if (!StringUtils.isEmpty(companyDTO.getAddress())) {
                        companyDTO.setAddressSimple(companyDTO.getAddress().substring(0, companyDTO.getAddress().lastIndexOf(".")));
                        companyDTO.setAddressDescription(companyDTO.getAddress().substring(companyDTO.getAddress().lastIndexOf(".") + 1));
                    }
                }

                //得到该公司的账户信息
                AccountInfo hotelAccountInfo = accountInfoMapper.selectByPrimaryKey(appHotelInfo.getOperatorId());
                if (null != hotelAccountInfo) {
                    accountDTO = MyBeanUtils.convert(hotelAccountInfo, AppAccountDTO.class);
                }

                //查询支付账户信息，在酒店的字段里面
                JsonHotelPayAccounts payAccounts = JSONObject.parseObject(appHotelInfo.getPayAccounts(), JsonHotelPayAccounts.class);
                if (null != payAccounts) {
                    payAccountsDTO = payAccounts.getPay_accounts();
                }
            }
        } else {

            //根据账号token的查询酒店
//            List<HotelInfo> hotelInfoList = hotelInfoMapper.selectByOperator(accountInfo.getId());
//            if (!CollectionUtils.isEmpty(hotelInfoList)) {
                HotelInfo appHotelInfo = hotelInfoMapper.selectByHotelManager(accountInfo.getId());
                if (null != appHotelInfo) {
                    hotelInfoDTO = MyBeanUtils.convert(appHotelInfo, AppHotelInfoDTO.class);
                    //查询支付账户信息，在酒店的字段里面
                    JsonHotelPayAccounts payAccounts = JSONObject.parseObject(appHotelInfo.getPayAccounts(), JsonHotelPayAccounts.class);
                    if (null != payAccounts) {
                        payAccountsDTO = payAccounts.getPay_accounts();
                    }
                }
        //    }
        }
        //存入图片信息
        hotelInfoDTO = this.convertAppHotelDTO(hotelInfoDTO);
        //公司资质
        if (null != companyDTO && null != companyDTO.getPrincipalInfo()) {
            JsonPrincipalInfo principalInfo = JSONObject.parseObject(companyDTO.getPrincipalInfo(), JsonPrincipalInfo.class);
            if (null != principalInfo) {
                companyDTO.setPrincipalInfoDTO(MyBeanUtils.convert(principalInfo, AppPrincipalInfoDTO.class));
            }
        }

        detailDTO.setAppHotelInfoDTO(hotelInfoDTO);
        detailDTO.setAppCompanyDTO(companyDTO);
        detailDTO.setAppAccountDTO(accountDTO);
        detailDTO.setPayAccountsDTO(payAccountsDTO);
        return CommonResult.success(detailDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateHotel(UpdateHotelInfoParam param, AccountInfo accountInfo) {

        //只能酒店自己才能修改
        if (accountInfo.getType() != AccountType.HotelManager) {
            return CommonResult.create(null, CommonResult.NO_PERMISSION, "没有权限访问");
        }
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(param.getId());
        if (null != hotelInfo) {
            hotelInfo.setContactName(param.getContactName());
            hotelInfo.setDescription(param.getDescription());
            hotelInfo.setRemark(param.getRemark());
            hotelInfo.setStartDateNotax(DateUtils.toDateTime(param.getStartDateNotax()));
            hotelInfo.setEndDateNotax(DateUtils.toDateTime(param.getEndDateNotax()));
            hotelInfo.setPhone(param.getPhone());
            hotelInfo.setTel(param.getTel());
            JsonHotelExtraInfo extraInfo = JSONObject.parseObject(hotelInfo.getExtraInfo(), JsonHotelExtraInfo.class);
            extraInfo.setDevices(param.getDevices());
            extraInfo.setImgUrlList(param.getHotelPics());
            hotelInfo.setExtraInfo(JSONObject.toJSONString(extraInfo));

            int count = hotelInfoMapper.update(hotelInfo,
                    new UpdateWrapper<HotelInfo>().eq(HotelInfo.ID, hotelInfo.getId()));
            if (count > 0) {
                //更新账户表中的手机号
                accountInfoMapper.update(new AccountInfo().setPhone(param.getPhone()),
                        new UpdateWrapper<AccountInfo>().eq(AccountInfo.ID, hotelInfo.getOperatorId()));
                return CommonResult.success(null, "操作成功");
            }
        }
        return CommonResult.failed("保存酒店数据失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult validHotel(UpdateValidHotelParam param, AccountInfo accountInfo, Boolean valid) {

        if (accountInfo.getType() == AccountType.HotelManager) {
            return CommonResult.create(null, CommonResult.NO_PERMISSION, "没有权限访问");
        }
        //查询酒店，同步查询酒店账号
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(param.getId());
        if (null != hotelInfo) {
            AccountInfo hotelAccountInfo = accountInfoMapper.selectByPrimaryKey(hotelInfo.getOperatorId());
            //是否有值，然后取反，后期可以删除
            if (valid == null) {
                if (hotelInfo.getValid()) {
                    hotelInfo.setValid(false);
                    hotelAccountInfo.setValid(false);
                } else {
                    hotelInfo.setValid(true);
                    hotelAccountInfo.setValid(true);
                }
            } else {
                hotelInfo.setValid(valid);
                hotelAccountInfo.setValid(valid);
            }
            int count = hotelInfoMapper.update(hotelInfo,
                    new UpdateWrapper<HotelInfo>().eq(HotelInfo.ID, hotelInfo.getId()));
            if (count > 0) {
                //禁用/启用账号
                int countAccount = accountInfoMapper.update(hotelAccountInfo,
                        new UpdateWrapper<AccountInfo>().eq(AccountInfo.ID, hotelAccountInfo.getId()));
                if (countAccount > 0) {
                    if (!hotelAccountInfo.getValid()) {
                        //清空该账户的token, 并且不能登录
                        String key = BuilderKey.build(ACCOUNT_TOKEN, hotelAccountInfo.getId());
                        redisService.remove(key);
                    }
                }
                return CommonResult.success(null, "操作数据成功");
            }
        }
        return CommonResult.failed("没有该酒店的数据信息，操作失败");
    }

    @Override
    public CommonResult<List<AppHotelTypeDTO>> getHotelType(AccountInfo accountInfo) {

        List<AppHotelTypeDTO> appHotelTypeDTOList = Lists.newArrayList();

        List<HotelTypeEnum> h = Arrays.asList(HotelTypeEnum.values());

        h.forEach(hotelTypeEnum -> {
            AppHotelTypeDTO hotelTypeDTO = new AppHotelTypeDTO();
            hotelTypeDTO.setType(hotelTypeEnum.getCode());
            hotelTypeDTO.setValue(hotelTypeEnum.getMsg());
            appHotelTypeDTOList.add(hotelTypeDTO);
        });

        return CommonResult.success(appHotelTypeDTOList);
    }

    @Override
    public CommonResult<List<AppStarLevelDTO>> getStarLevel(AccountInfo convert) {

        List<AppStarLevelDTO> appStarLevelDTOList = Lists.newArrayList();

        List<StarLevelEnum> h = Arrays.asList(StarLevelEnum.values());

        h.forEach(starLevelEnum -> {
            AppStarLevelDTO starLevelDTO = new AppStarLevelDTO();
            starLevelDTO.setType(String.valueOf(starLevelEnum.getValue()));
            starLevelDTO.setValue(starLevelEnum.getDesc());
            appStarLevelDTOList.add(starLevelDTO);
        });

        return CommonResult.success(appStarLevelDTOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateRoomNote(SetRoomNoteParam param, AccountInfo accountInfo) {
        int count = 0;
        if (null != accountInfo && accountInfo.getType() == AccountType.HotelManager) {

//            List<HotelInfo> hotelInfoList = hotelInfoMapper.selectByOperator(accountInfo.getId());
//            if (!CollectionUtils.isEmpty(hotelInfoList)) {
                HotelInfo appHotelInfo = hotelInfoMapper.selectByHotelManager(accountInfo.getId());
                if (null != appHotelInfo) {
                    JsonHotelExtraInfo extraInfo = JSONObject.parseObject(appHotelInfo.getExtraInfo(), JsonHotelExtraInfo.class);
                    extraInfo.setCheckinTime(param.getCheckinTime());
                    extraInfo.setCheckoutTime(param.getCheckoutTime());
                    extraInfo.setExtraNote(param.getExtraNote());
                    //转换成json
                    appHotelInfo.setExtraInfo(JSONObject.toJSONString(extraInfo));
                    count = hotelInfoMapper.update(appHotelInfo,
                            new UpdateWrapper<HotelInfo>().eq(HotelInfo.ID, appHotelInfo.getId()));

                    if(count > 0){
                        List<String> sourceIds = Lists.newArrayList();
                        sourceIds.add(String.valueOf(appHotelInfo.getId()));
                        //更新酒店的相关备注信息，发送Mq更新ES
                        mqProducerService.sendEsUpdate(new EsUpdateMessage().setType("hotel")
                                .setSourceType("yyks").setSourceIds(sourceIds),0);

                        return CommonResult.success(null, "更新成功");
                    }
                }
         //   }
        }
        return CommonResult.failed("操作失败!");
    }

    @Override
    public CommonResult<AppRoomNoteDTO> getRoomNote(AccountInfo accountInfo) {
        AppRoomNoteDTO roomNoteDTO = new AppRoomNoteDTO();
        if (null != accountInfo && accountInfo.getType() == AccountType.HotelManager) {

//            List<HotelInfo> hotelInfoList = hotelInfoMapper.selectByOperator(accountInfo.getId());
//            if (!CollectionUtils.isEmpty(hotelInfoList)) {
                //得到字符串
                HotelInfo appHotelInfo = hotelInfoMapper.selectByHotelManager(accountInfo.getId());
                if (null != appHotelInfo) {
                    String extraInfo = appHotelInfo.getExtraInfo();
                    JsonHotelExtraInfo hotelExtraInfo = JSONObject.parseObject(extraInfo, JsonHotelExtraInfo.class);
                    if (null != hotelExtraInfo) {
                        roomNoteDTO.setCheckinTime(hotelExtraInfo.getCheckinTime());
                        roomNoteDTO.setCheckoutTime(hotelExtraInfo.getCheckoutTime());
                        roomNoteDTO.setExtraNote(hotelExtraInfo.getExtraNote());
                    }
                }
          //  }
        }
        return CommonResult.success(roomNoteDTO);
    }

    /**
     * 酒店设置是否手动抢单
     *
     * @param loginUser 当前登录用户
     * @param isRob     0自动抢单，1手动抢单
     */
    @Override
    public void isRob(AccountInfo loginUser, Integer isRob) {
        HotelInfo hotelInfo = getHotelInfoAccountHotelInfo(loginUser);
        if (null != hotelInfo.getManualPickOrder()) {
            if (hotelInfo.getManualPickOrder().equals(isRob)) {
                if (0 == isRob) {
                    throw new ServiceException("已是自动抢单状态");
                }
                if (1 == isRob) {
                    throw new ServiceException("已是手动抢单状态");
                }
            }
            hotelInfo.setManualPickOrder(isRob);
            if (1 != baseMapper.updateById(hotelInfo)) {
                throw new ServiceException("更新抢单状态异常");
            }
            mqProducerService.sendEsUpdate(new EsUpdateMessage().setType("hotel").setSourceType("yyks").setSourceIds(Lists.newArrayList(String.valueOf(hotelInfo.getId()))),0);
        }
    }

    /**
     * 查看酒店抢单状态
     *
     * @param loginUser 当前登录用户
     * @return
     */
    @Override
    public Integer robStatus(AccountInfo loginUser) {
        HotelInfo hotelInfo = getHotelInfoAccountHotelInfo(loginUser);
        return hotelInfo.getManualPickOrder() == null ? 0 : hotelInfo.getManualPickOrder();
    }

    /**
     * 通过酒店id查询酒店账户id
     *
     * @param hotelId
     * @return
     */
    @Override
    public Integer selectOperatorIdByHotelId(Integer hotelId) {
        HotelInfo hotelInfo = baseMapper.selectById(hotelId);
        return hotelInfo.getOperatorId();
    }

    /**
     * 判断酒店是否在免佣期
     *
     * @param gmtCreate
     * @param hotelId
     * @return
     */
    @Override
    public boolean isInNoFeeDate(Date gmtCreate, Integer hotelId) {
        if (null == gmtCreate) {
            return true;
        }
        HotelInfo hotelInfo = baseMapper.selectById(hotelId);
        if (null == hotelInfo) {
            return true;
        }
        long time = gmtCreate.getTime();
        //如果免佣期未设置则认为不在免佣期间
        if (null == hotelInfo.getStartDateNotax() || null == hotelInfo.getEndDateNotax()) {
            return false;
        }
        if (time >= hotelInfo.getStartDateNotax().getTime() && time <= hotelInfo.getEndDateNotax().getTime()) {
            log.info("查询到的酒店免佣期hotelId = {}", hotelId);
            return true;
        }
        return false;
    }

    /**
     * 全国酒店星级
     *
     * @return
     */
    @Override
    public List<DataScreenHotelStarResult> statStar() {
        //舒适度 1舒适 2高档 3豪华 4民宿专区
        List<DataScreenHotelStarResult> results = Lists.newArrayList();
        HotelCountParam param = new HotelCountParam();
        param.setComfortLevel(1);
        results.add(new DataScreenHotelStarResult(1, mySearchService.searchHotelCount(param)));
        param.setComfortLevel(2);
        results.add(new DataScreenHotelStarResult(2, mySearchService.searchHotelCount(param)));
        param.setComfortLevel(3);
        results.add(new DataScreenHotelStarResult(3, mySearchService.searchHotelCount(param)));
        param.setComfortLevel(4);
        results.add(new DataScreenHotelStarResult(4, mySearchService.searchHotelCount(param)));
        return results;
    }

    @Override
    public List<DataGreenVipHotelMonthResult> statVipHotelSixMonth() {

        return this.baseMapper.statVipHotelSixMonth();
    }

    /**
     * 酒店相关信息转换
     *
     * @param hotelInfoDTO 酒店DTO
     * @return
     */
    private AppHotelInfoDTO convertAppHotelDTO(AppHotelInfoDTO hotelInfoDTO) {
        if (null != hotelInfoDTO && null != hotelInfoDTO.getExtraInfo()) {
            JsonHotelExtraInfo extraInfo = JSONObject.parseObject(hotelInfoDTO.getExtraInfo(), JsonHotelExtraInfo.class);
            if (!CollectionUtils.isEmpty(extraInfo.getImgUrlList())) {
                hotelInfoDTO.setHotelPics(extraInfo.getImgUrlList());
            }
            //存入服务信息
            List<AppRoomDevicesDTO> devicesList = Lists.newArrayList();
            if (!StringUtils.isEmpty(extraInfo.getDevices())) {
                String[] devices = extraInfo.getDevices().split(",");
                StringBuilder devicesCn = new StringBuilder();
                for (String en : devices) {
                    AppRoomDevicesDTO devicesDTO = new AppRoomDevicesDTO();
                    devicesDTO.setType(en);
                    devicesDTO.setValue(DevicesEnum.getCNByEN(en));
                    devicesList.add(devicesDTO);
                    devicesCn.append(DevicesEnum.getCNByEN(en)).append(",");
                }
                hotelInfoDTO.setDevices(extraInfo.getDevices());
                hotelInfoDTO.setDevicesCn(devicesCn.toString().substring(0, devicesCn.length() - 1));
                hotelInfoDTO.setDevicesList(devicesList);
            }
            //截取地址信息存入信息中
            String firstAddress = "";
            String lastAddress = "";
            if (!StringUtils.isEmpty(hotelInfoDTO.getAddress())) {
                firstAddress = hotelInfoDTO.getAddress().substring(0, hotelInfoDTO.getAddress().lastIndexOf("."));
                lastAddress = hotelInfoDTO.getAddress().substring(hotelInfoDTO.getAddress().lastIndexOf(".") + 1);
            }
            hotelInfoDTO.setAddressSimple(firstAddress);
            hotelInfoDTO.setAddressDescription(lastAddress);

            //存入类型信息
            if (null != hotelInfoDTO.getType()) {
                String typeName = HotelTypeEnum.getMsgByCode(hotelInfoDTO.getType().toString());
                hotelInfoDTO.setTypeName(typeName);
            }
            if (null != hotelInfoDTO.getStarLevel()) {
                String levelName = StarLevelEnum.getDesc(hotelInfoDTO.getStarLevel());
                hotelInfoDTO.setStarLevelName(levelName);
            }
        }
        return hotelInfoDTO;
    }


    /**
     * 组装查询数据
     *
     * @param queryHotelParam 酒店输入参数
     * @param accountInfo     操作人
     * @return 返回结果
     */
    private Map<String, Object> convertQueryMap(QueryHotelParam queryHotelParam, AccountInfo accountInfo) {

        Map<String, Object> queryMap = Maps.newHashMap();
        if (null != queryHotelParam && null != accountInfo) {
            queryMap = ObjectConvertUtil.objectToMap(queryHotelParam);
            //存入登录账户类型
            assert queryMap != null;
            queryMap.put("type", accountInfo.getType());

            //根据区域查酒店
            String areaType = null;
            CommonResult<AppAddressDTO> addressByDivId = addressDivisionService.getAddressByDivId(queryHotelParam.getDivCode());
            if (null != addressByDivId.getData()) {
                areaType = addressByDivId.getData().getDivLevel();
            }
            queryMap.put("areaType", areaType);
            queryMap.put("accountId", accountInfo.getId());
            if(null != queryHotelParam.getVipFlag()){
                //当访问用户不是总公司时，查询所有类型的酒店
                if(accountInfo.getType() == AccountType.Administrator){
                    queryMap.put("vipFlag", queryHotelParam.getVipFlag());
                }else{
                    queryMap.put("vipFlag", null);
                }
            }

        }

        return queryMap;
    }
}
